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
156 views
in Technique[技术] by (71.8m points)

reactjs - How to add a field to each object in array and push that result array to another array using react and javascript?

i want to add a field type to each object in an array and push the result to another array and push that to another array.

below is how the array of object looks,

const arrObj1 = [
    {
        id: '1',
        name: 'n1',
    },
    {
        id: '2',
        name: 'n2',
    }
]

const arrObj2 = [
    {
        id: '3',
        name: 'n3',
    },
    {
        id: '4',
        name: 'n4',
    }
]

what i am trying to do?

i want to add a type field with value 'type1' to arrObj1 and type field with value 'type2' to arrObj2

so the output should be like below,

const arrObj1 = [
    {
        id: '1',
        name: 'n1',
        type: 'type1',
    },
    {
        id: '2',
        name: 'n2',
        type: 'type1',
    }
]

const arrObj2 = [
    {
        id: '3',
        name: 'n3',
        type: 'type2',
    },
    {
        id: '4',
        name: 'n4',
        type: 'type2',
    }
]

then i want to combine these two arrays arrObj1 and arrObj2 into one array like below

const combinedArrObj = [
    {
        id: '1',
        name: 'n1',
        type: 'type1',
    },
    {
        id: '2',
        name: 'n2',
        type: 'type1',
    },
    {
        id: '3',
        name: 'n3',
        type: 'type2',
    },
    {
        id: '4',
        name: 'n4',
        type: 'type2',
    }
]

what i have tried?

const arrObj1Res = arrObj1.map((obj: any) => {
    return {
        ...arrObj1,
        type: 'type1',
    }
});
const arrObj2Res = arrObj2.map((obj: any) => {
    return {
        ...arrObj2,
        type: 'type2',
    }
});
const combinedArrObj = [
    ...arrObj1Res,
    ...arrObj2Res,
];

this works. but how can i refactor to something simple rather than adding field type for each obj in array and then combine

could someone help me with this. thanks.

question from:https://stackoverflow.com/questions/65920645/how-to-add-a-field-to-each-object-in-array-and-push-that-result-array-to-another

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

1 Reply

0 votes
by (71.8m points)

you can use this

let result=arrObj1.concat(arrObj2)
function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
        }
    }
    return false;
}
result.filter(element => {
      if (contains(arrObj1,element) ){
        element.type='type1'
        return element
      }else {
        element.type='type2'
        return element
      }
});

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

...