我得到以下对象数组,如何将它们创建/拆分为多个对象数组。我们必须检查serialNumbers的内部数组是否不为空然后我们必须创建一个新对象,该对象将包含外部数组对象的旧数据加上内部数组对象的第一个值等等......
0: {id: 288, name: "22", price: 3, Inventories: Array(1), SerialNumbers: Array(2)}
1: {id: 289, name: "3", Price: 3, Inventories: Array(1), SerialNumbers: Array(0)}
2: {id: 290, name: "4", Price: 3, Inventories: Array(1), SerialNumbers: Array(0)}
我想实现这样的目标
0: {id: 288, name: "22", price: 3, Inventories: Array(1), SerialNumbers:1 }
1: {id: 288, name: "22", price: 3, Inventories: Array(1), SerialNumbers:2 }
2: {id: 289, name: "3", Price: 3, Inventories: Array(1), SerialNumbers: null}
3: {id: 290, name: "4", Price: 3, Inventories: Array(1), SerialNumbers: null}
我试过这个,但我无法达到结果。
this.data = response.map((obj) => {
return {...obj, ... obj.VariantSerialNumbers}
});
答案 0 :(得分:1)
也许是这样的:
this.data = response.map((value, index) => {
if (!!value.SerialNumbers.length)
return value.SerialNumbers.map((number) => {
let obj = Object.assign({}, value);
obj.SerialNumbers = number;
return obj;
})
value.SerialNumbers = null;
return value;
}).flatten()
首先映射到根数组,然后映射到 SerialNumbers(如果存在)。然后将结果展平以“撤消”嵌套数组结果。