[英]creating an object of arrays and values from an array of objects containing arrays and values in javascript
In the following code snippet, I am gathering variables from an array of objects and then combining them into a single new object with other variables.在以下代码片段中,我从对象数组中收集变量,然后将它们与其他变量组合成一个新对象。 Here is a simplified example:
这是一个简化的示例:
var y = 10; var x = [ {name: "name1", values:[1,2,3]}, {name: "name2", values:[3,4,5]} ]; var newObj = {y:[],x:[]} for (var j=0;j<x.length;j++){ newObj.x.push([]) for (var i=0;i<x[j].values.length;i++){ newObj.x[j].push(x[j].values[i]); } } newObj.y=y console.log(newObj)
This works for what I am doing, but I am sure it is not even remotely best practices.这适用于我正在做的事情,但我确信它甚至不是远程最佳实践。 What would be a more elegant way of organizing the values array from x into the new object with the single value for y?
使用 y 的单个值将值数组从 x 组织到新对象中的更优雅的方法是什么?
ES6: ES6:
You can use Array.map()
to get an array of x
values, and assign y
using computed property names .您可以使用
Array.map()
获取x
值数组,并使用计算属性名称分配y
。
Note: I use ES6's arrow function , and object destructuring in the map's callback, but it's not a must.注意:我在地图的回调中使用了 ES6 的箭头函数和对象解构,但这不是必须的。 See ES5 version.
请参阅 ES5 版本。
const y = 10; const x = [ {name: "name1", values:[1,2,3]}, {name: "name2", values:[3,4,5]} ]; const result = { y, x: x.map(({ values }) => values) // [...values] if you want a copy of the original values }; console.log(result);
ES5: ES5:
Use Array.map()
to get x
values:使用
Array.map()
获取x
值:
var y = 10; var x = [ {name: "name1", values:[1,2,3]}, {name: "name2", values:[3,4,5]} ]; var result = { y: y, x: x.map(function(o) { return o.values; // values.slice(0) if you want a copy of the original values }) }; console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.