我在这里努力解决问题。 假设我有一个像这样的对象数组:
[
{name:Alex, products: [{type: 1, code: 1213}, {type: 2, code: 2312}]},
{name:Alex, products: [{type: 1, code: 1213}, {type: 2, code: 2312}]}
]
我想以某种方式重建我的对象是这样的:
[
{name:Alex, products: [{name:Alex, type: 1, code: 1213}, {name:Alex, type: 2, code: 2312}]},
{name:Alex, products: [{{name:Alex, type: 1, code: 1213}, {{name:Alex, type: 2, code: 2312}]}
]
所以每个嵌套数组都包含名称。这可能在javascript中吗?
答案 0 :(得分:1)
我想以某种方式重建我的对象,以便成为类似的东西 这样:
使用地图
arr.map( s => (s.products.map( i => (i.name = s.name, i) ), s) );
<强>演示强>
var arr = [{
name: "Alex",
products: [{
type: 1,
code: 1213
}, {
type: 2,
code: 2312
}]
},
{
name: "Alex",
products: [{
type: 1,
code: 1213
}, {
type: 2,
code: 2312
}]
}
]
var output = arr.map(s => (s.products.map(i => (i.name = s.name, i)), s));
console.log(output);
&#13;
答案 1 :(得分:1)
您可以使用Object.assign
创建新的数组/对象。
var data = [{ name: 'Alex', products: [{ type: 1, code: 1213 }, { type: 2, code: 2312 }] }, { name: 'Alex', products: [{ type: 1, code: 1213 }, { type: 2, code: 2312 }] }],
converted = data.map(o => Object.assign(
{},
o,
{ products: o.products.map(p => Object.assign({ name: o.name }, p)) }
));
console.log(converted);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:1)
您可以使用Array.map()
的嵌套Object.assign()
调用来创建新数组,而无需更改原始数据:
const data = [{"name":"Alex","products":[{"type":1,"code":1213},{"type":2,"code":2312}]},{"name":"Alex","products":[{"type":1,"code":1213},{"type":2,"code":2312}]}]
const result = data.map((o) => Object.assign({}, o, {
products: o.products.map((p) => Object.assign({ name: o.name }, p))
}))
console.log(result)
&#13;
如果您只想更改(mutate)当前数组,请使用嵌套的Array.forEach()
调用:
const data = [{"name":"Alex","products":[{"type":1,"code":1213},{"type":2,"code":2312}]},{"name":"Alex","products":[{"type":1,"code":1213},{"type":2,"code":2312}]}]
data.forEach((o) => o.products.forEach((p) => p.name = o.name));
console.log(data)
&#13;
答案 3 :(得分:1)
您可以在对象中使用带有扩展语法的map()
方法来创建包含更新对象的新数组并保留原始数据。
const data = [
{name:'Alex', products: [{type: 1, code: 1213}, {type: 2, code: 2312}]},
{name:'Alex', products: [{type: 1, code: 1213}, {type: 2, code: 2312}]}
]
const result = data.map(e => ({
...e,
products: e.products.map(p => {
return {...p, name: e.name}
})
}))
console.log(result)
&#13;
答案 4 :(得分:1)
你有名字属性的错字.Alex应该是'Alex'(字符串)。你可以从两个数组方法中获得帮助。 Array.prototype.map()
和Array.prototype.forEach()
实现目标
var initialArr = [
{name:'Alex1', products: [{type: 1, code: 1213}, {type: 2, code: 2312}]},
{name:'Alex2', products: [{type: 1, code: 1213}, {type: 2, code: 2312}]}
]
var newArr = initialArr.map(function(elem){
elem.products.forEach(function(obj){
obj.name = this.name
},elem)
return elem
})
console.log(newArr)