H5W3
当前位置:H5W3 > 其他技术问题 > 正文

数据间字段,值的转换


  var arr = [
        {name: 'color', value: 'red', position: 1},
        {name: 'size', value: 's', position: 2},
        {name: 'price', value: 20, position: 3}
      ]

      var list = [
        {id: 11, color: 'red' },
        {id: 12, size: 's' },
        {id: 13, price: 200 },
        {id: 14, size: 'm' },
        {id: 15, color: 'pink' },
        {id: 16, price: 10 },
      ]

    position: 1, 代表 字段option1,position: 2, 代表 字段option2, 
    position: 3, 代表 字段option3,
    如何把list 转成
    list = [
        {id: 11, option1: 'red' },
        {id: 12, option2: 's' },
        {id: 13, option3: 200 },
        {id: 14, option2: 'm' },
        {id: 15, option1: 'pink' },
        {id: 16, option3: 10 },
      ]
      虽然小问题 ,但是想不到好方法去转换.
      
这是一时乱写的, 知道是错的, 但没有其他思路。请大家帮忙看看
list.forEach((item, index) => {
        if ( item.option1 == undefined ||item.option2 == undefined||item.option3 == undefined) {
          list.forEach((sub, subindex) => {
            if (sub.name == "color" && item.color !== undefined) {
              item["option" + (subindex + 1)] = item.color;
            }
            if (sub.name == "size" && item.size !== undefined) {
              item["option" + (subindex + 1)] = item.size;
            }
            if (sub.name == "price" && item.price !== undefined) {
              item["option" + (subindex + 1)] = item.price;
            }
          });
        }
      });
      

回答:

list.map(item => {

  const { id } = item
  const [_, key] = Object.keys(item)
  const value = item[key]
  let obj = { id }

  const { position } = arr.find(({ name }) => name === key) || {}

  if (position) {
    obj[`option${position}`] = value
  }
  return obj
  
})

回答:

for (var i = 0; i < list.length; i++) {
    var key, value, position, a = list[i];
    for (var _key in a) {
        if (_key !== "id") {
            key = _key;
            value = a[_key];
            delete a[_key];
            break;
        }
    }
    for (var j = 0; j < arr.length; j++) {
        var b = arr[j];
        var name = b.name;
        if (name === key) {
            position = b.position;
            break;
        }
    }
    a["option" + position] = value;
}
console.log(list);

本文地址:H5W3 » 数据间字段,值的转换

评论 0

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址