0

I have a javascript array as

arr = [{"class":"a"},{"sub_class":"b"},{"category":"c"},{"sub_category":"d"}]

I want a new array as:

new_arr = [{"class":"a", "sub_class":"b", "category":"c", "sub_category":"d"}]

Is it possible to do this in Javascript without using a for loop to iterate through arr?

2
  • 2
    Why is it still an array if you only have one element in it? Commented Jul 8, 2020 at 16:08
  • 1
    Because I might need to push new dictionaries to the array later Commented Jul 8, 2020 at 16:08

3 Answers 3

6

You can use Object.assign:

const array = [{
  "class": "a"
}, {
  "sub_class": "b"
}, {
  "category": "c"
}, {
  "sub_category": "d"
}]

const mergedObject = Object.assign({}, ...array);

// And put in an Array if that was intentional
const newArray = [mergedObject];

console.log(newArray);

Sign up to request clarification or add additional context in comments.

Comments

1

I think that you want to merge objects. You could either use a spread operator or Object.assign. I don't see the point of having a single object inside an array. Considering your requirements you could do:

const merged = arr.reduce((list, curr) => {
   return Object.assign({}, list, curr);
}, {});

const newArr = [merged];

Comments

1

You can try this.

var arr = [{"class":"a"},{"sub_class":"b"},{"category":"c"},{"sub_category":"d"}];
var res=[];
var res1=[];
res=Object.assign(...arr);
res1.push(res);

console.log("Result: ",res1);

1 Comment

Just be aware that this mutates the first object in arr, which you may or may not care about. Passing {} as the first element will make sure you're creating a new object and are assigning to that.

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.