0

How to merge the array of objects to another array of objects in JavaScript

Hi everyone, below I added my code.

   

    var person=[{"name":"Billy","age":34},{"name":"Billy","age":34}];
       var clothing=[{"shoes":"nike","shirt":"long sleeve"}, 
       {"shoes":"nike","shirt":"long sleeve"}];

3
  • 1
    w3schools.com/jsref/jsref_concat_array.asp Commented Jan 5, 2022 at 13:29
  • 1
    Seems a pretty odd requirement to have an array of objects where not all of the objects represent the same things - are you sure you're not really wanting to merge the objects themselves together so each person has their clothing? like {"name":"Billy","age":34,"shoes":"nike","shirt":"long sleeve"} Commented Jan 5, 2022 at 13:32
  • Agree with @Jamiec, also note that, in this case, you can remove double quotes from key names. Commented Jan 5, 2022 at 13:39

3 Answers 3

2

you can use spread operator for this

const merged = [...person,...clothing]
Sign up to request clarification or add additional context in comments.

2 Comments

I applied the [...person,...clothing] code. But, Result comes like this [0] [{"name":"Billy","age":34},{"name":"Billy","age":34}]}] and [1] [{"shoes":"nike","shirt":"long sleeve"},{"shoes":"nike","shirt":"long sleeve"}]
if you will write [person, clothing] then you will get this. For your answer, you have to use the spread operator like [...person, ...clothing]
1
var person=[{"name":"Billy","age":34},{"name":"Billy","age":34}];
var clothing=[{"shoes":"nike","shirt":"long sleeve"},{"shoes":"nike","shirt":"long sleeve"}];


var mergedV1 = [...person, ...clothing]
var mergedV2 = person.concat(clothing)

Comments

1

Use spread ES6 syntax https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Spread_syntax

var person=[{"name":"Billy","age":34},{"name":"Billy","age":34}];
var clothing=[{"shoes":"nike","shirt":"long sleeve"},{"shoes":"nike","shirt":"long sleeve"}];

var merge = [...person, ...clothing]
console.log(merge)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.