angularjs 如何将父对象的id推送到子对象?

bmp9r5qi  于 2023-10-15  发布在  Angular
关注(0)|答案(5)|浏览(101)

我有一个对象数组,它有一个内部对象数组,我想把父对象的id推到每个子对象。

a = [
        {id: 'abc', stage: [{name: 'car' , value: '123'},{name: 'bus' , value: '345'},{name: 'truck' , value: '567'}],
        {id: 'def', stage: [{name: 'bike' , value: '890'},{name: 'cycle' , value: '123'},{name: 'car' , value: '456'}]}
    ]

expected output = [
    {name: 'car' , value: '123', id: 'abc'},{name: 'bus' , value: '345', 'abc'},{name: 'truck' , value: '567', 'abc'}, {name: 'bike' , value: '890', id: 'def'},{name: 'cycle' , value: '123',id: 'def',id: 'def'},{name: 'car' , value: '456', id: 'def'}
]

我能够得到唯一的阶段,但不能推id到每个对象。请帮助

const getAllStages = [].concat(...map(a, el => el.stage));
console.log(getAllStages )
omqzjyyz

omqzjyyz1#

再次使用.map()el.id添加到el.stage的每个元素。
您可以在外部Map中使用.flatMap()将所有结果连接到一个数组中。

const a = [
    {id: 'abc', stage: [{name: 'car' , value: '123'},{name: 'bus' , value: '345'},{name: 'truck' , value: '567'}]},
    {id: 'def', stage: [{name: 'bike' , value: '890'},{name: 'cycle' , value: '123'},{name: 'car' , value: '456'}]}
]

result = a.flatMap(({
  id,
  stage
}) => stage.map(s => ({
  id: id,
  ...s
})));

console.log(result);
64jmpszr

64jmpszr2#

如果您尝试在id中合并:

let remapped = a.map(e => ({ id: a.id, ...e }));

其中,它将每个条目转换为一个对象,继承a.id值,并添加对象中的任何其他内容。

nhjlsmyf

nhjlsmyf3#

下面是一个例子和结果:)

a.forEach(function(row) {
    row.stage.map(function (child) {child.id = row.id})
})

结果:

[{"id":"abc","stage":[{"name":"car","value":"123","id":"abc"},{"name":"bus","value":"345","id":"abc"},{"name":"truck","value":"567","id":"abc"}]},{"id":"def","stage":[{"name":"bike","value":"890","id":"def"},{"name":"cycle","value":"123","id":"def"},{"name":"car","value":"456","id":"def"}]}]
hsvhsicv

hsvhsicv4#

您可以这样编写而不使用库

let a = [
    {
        id: 'abc', stage:
            [
                { name: 'car', value: '123' },
                { name: 'bus', value: '345' },
                { name: 'truck', value: '567' }
            ]
    },
    {
        id: 'def', stage:
            [
                { name: 'bike', value: '890' },
                { name: 'cycle', value: '123' },
                { name: 'car', value: '456' }
            ]
    }
]    
let output = [];
    for (const element of a) {
        for (const stageElement of element.stage) {
            let newElement = {
                name: stageElement.name,
                value: stageElement.value,
                id: element.id
            };
            output.push(newElement);
        }
    }
hjzp0vay

hjzp0vay5#

const a = [
    {id: 'abc', stage: [{name: 'car' , value: '123'},{name: 'bus' , value: '345'},{name: 'truck' , value: '567'}]},
    {id: 'def', stage: [{name: 'bike' , value: '890'},{name: 'cycle' , value: '123'},{name: 'car' , value: '456'}]}
]

a.forEach(item => {
    const itemId = item.id;
    const stages = item.stage;

    stages.forEach(stage => {
        stage['id'] = itemId;
    })
});

console.log(a);

相关问题