如何将值数组指定为另一个值数组的键?

时间:2017-04-13 18:15:18

标签: javascript jquery angularjs arrays json

转换的最佳方式是什么,

{
   "columns":[
      "name",
      "color"
   ],
   "values":[
      [
         "lion",
         "yellow"
      ],
      [
         "crow",
         "black"
      ]
   ]
}

{
   "data":[
      {
        "name":"lion",
        "color":"yellow"
      },
      {
         "name":"crow",
         "color":"black"
      }
   ]
}

而不是循环,有没有可用的功能?我可以通过extend()吗?

来实现它

3 个答案:

答案 0 :(得分:4)

您可以将Object.assignspread syntax ...用于部分。



var object = { columns: ["name", "color"], values: [["lion", "yellow"], ["crow", "black"]] },
    result = { data: object.values.map(v => Object.assign(...object.columns.map((c, i) => ({[c]: v[i]})))) };

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:2)

你可以用map和reduce的组合来做。减少原始列数组将允许代码使用任意数量的列,它将通过索引获取相应的值:

const result = {data: data.values.map(el => {
  return data.columns.reduce((prev, curr, index) => {
    prev[curr] = el[index]
    return prev
  }, {})
})}

查看下面的演示。



const data = {
   "columns":[
      "name",
      "color"
   ],
   "values":[
      [
         "lion",
         "yellow"
      ],
      [
         "crow",
         "black"
      ]
   ]
}

const result = {data: data.values.map(el => {
  return data.columns.reduce((prev, curr, index) => {
    prev[curr] = el[index]
    return prev
  }, {})
})}

console.log(result)




答案 2 :(得分:2)

您可以使用解构赋值,spread元素获取.columns数组的值; for..of循环通过迭代原始对象的.columns属性将data数组的计算属性作为字符串分配为.values数组中对象的属性,将每个数组的值指定为值创建对象

let obj = {
   "columns":[
      "name",
      "color"
   ],
   "values":[
      [
         "lion",
         "yellow"
      ],
      [
         "crow",
         "black"
      ]
   ]
}

let [res, key, value] = [{data:Array()}, ...obj.columns];

for (let [a, b] of [...obj.values]) res.data.push({[key]:a, [value]:b});

console.log(res);