如何从arrayList中提取对象并添加到另一个arrayList中



我试图通过修改中的一个对象将一个数组列表转换为另一个

let array1 = [
{
name: "test",
address: "testaddress",
state: {
2022: {
January: { month_state: "pending" },
},
},
},
{
name: "test2",
address: "testaddress2",
state: {
2022: {
January: { month_state: "pending" },
},
},
},
];

我想转换成这个,哪种方式是正确的?谢谢

let array2 = [
{
name: "test",
address: "testaddress",
2022: {
January: { month_state: "pending" },
},
},
{
name: "test2",
address: "testaddress2",
2022: {
January: { month_state: "pending" },
},
},
];
let array2 = array1.map(({ state, ...rest }) => ({ ...rest, ...state }))

这个代码就可以了。

有几种方法可以实现您的要求。

我将向您展示使用.map的函数方法

let array1 = [
{
name: "test",
address: "testaddress",
state: {
2022: {
January: { month_state: "pending" }
}
}
},
{
name: "test2",
address: "testaddress2",
state: {
2022: {
January: { month_state: "pending" }
}
}
}
];
let array2 = array1.map((el) => {
const tmp = {
name: el.name,
adress: el.adress
};

// Here we iterate el.state, so we can extract each year.
/* We need to dynamically generate a property name (each year). 
So we use a feature called "computed property names (ES2015)" */
for (const prop in el.state) {
tmp[prop] = el.state[prop];
}
return tmp;
});
console.log(array2);

您也可以使用for循环,这也是一种有效的方法。

最新更新