简体   繁体   English

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

[英]How to assign Array of values as keys to another array of values?

What is the Best way to convert, 什么是最好的转换方式,

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

into

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

Rather than loop, Is there any function available ? 而不是循环,有没有可用的功能? Can I achieved it through something like extend() ? 我可以通过extend()之类的东西来实现它吗?

You could use Object.assign with spread syntax ... for the parts. 您可以使用带有扩展语法的 Object.assign ...作为部件。

 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; } 

You can do do it with combination of map and reduce. 你可以用map和reduce的组合来做。 Reducing original columns array will allow to code to work with any number of columns, it will pick up corresponding value by index: 减少原始列数组将允许代码使用任意数量的列,它将通过索引获取相应的值:

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

Check the demo below. 查看下面的演示。

 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) 

You can get vales of .columns array using destructuring assignment, spread element; 您可以使用解构赋值,spread元素获取.columns数组的值; for..of loop to assign computed properties of .columns array as strings as properties of objects at data array by iterating .values property of original object, assign value of each array as value of created object for..of循环,通过迭代原始对象的.values属性,将.columns数组的计算属性作为字符串分配为data数组中对象的属性,将每个数组的值赋值为创建对象的值

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM