gpt4 book ai didi

javascript - 从包含javascript中的数组和值的对象数组创建数组和值的对象

转载 作者:行者123 更新时间:2023-11-30 14:47:37 26 4
gpt4 key购买 nike

在下面的代码片段中,我从对象数组中收集变量,然后将它们与其他变量组合成一个新对象。这是一个简化的示例:

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)

这适用于我正在做的事情,但我确信它甚至不是最佳实践。将 x 中的值数组组织到具有单个 y 值的新对象中,有什么更优雅的方法?

最佳答案

ES6:

您可以使用 Array.map()获取 x 值的数组,并使用 computed property names 分配 y .

注意:我使用 ES6 的 arrow function , 和 object destructuring在 map 的回调中,但这不是必须的。请参阅 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:

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

关于javascript - 从包含javascript中的数组和值的对象数组创建数组和值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48654182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com