Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

javascript - Return a subarray with a value changed to reflect parent object

I am trying to change the value of single key in an associative array which is inside another assoc array using javascript. I have an array like this:

let arr = [{
    id: 4,
    name: 'test',
    docs: [{
        id: 1,
        name: 'abc'
      },{
        id: 2,
        name: 'xyz'
    }]
}, {
    id: 8,
    name: 'test2',
    docs: [{
        id: 5,
        name: 'abc'
      },{
        id: 7,
        name: 'xyz'
    }]
}]

I want to change the value of name of xyz to xyz (test), where test is name key of parent object and get final array as Output:

[{
    id: 1,
    name: 'abc (test)'
},
{
    id: 2,
    name: 'xyz (test)'
},
{
    id: 5,
    name: 'abc (test2)'
},
{
    id: 7,
    name: 'xyz (test2)'
}]

I am using approach.

let docs = new Array();
arr.forEach((item, index) => {
    let docx = item.documents.map(item1 => {
        item1.name = item1.name + " ("+item.name+")"; 
    });
    docs.push(docx);
});
return docs;

this is returning array of undefined array.

question from:https://stackoverflow.com/questions/65883400/return-a-subarray-with-a-value-changed-to-reflect-parent-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try a flatMap

let arr = [{ id: 4, name: 'test', docs: [{ id: 1, name: 'abc' },{ id: 2, name: 'xyz' }] }, { id: 8, name: 'test2', docs: [{ id: 5, name: 'abc' },{ id: 7, name: 'xyz' }] }]
const output = arr.flatMap(item =>
  item.docs.map(({id,name}) => ({ id, name: `${name} (${item.name})` }))
)
console.log(output)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...