0
  var note = {
      text: "test 1",
      badges: ["testing", "111"],
    };
    var note2 = {
      text: "test 2",
      badges: ["testing", "222"],
    };

    var newData = {...note, ...note2}

    console.log("newData :", newData);

The output is not what im looking for, it overwrites it and only shows the last obj. Im expecting like having both objects on a single one or should I use an array for that instead?

2
  • what's your expected result? Commented Feb 10, 2021 at 5:49
  • You cannot have same keys in a single object. If there are then the last one overrides the earlier ones. So, here in this case you have text in note and note2 as well and when you do this {...note, ...note2}, note2's text overrides the easier note.text. Commented Feb 10, 2021 at 5:49

3 Answers 3

1

The spread syntax ...note puts the keys of note into newData, so it looks exactly like note at that point. Then ...note2 overwrites those values with the contents of note2. So you can do:

var newData = {note, note2};

which gives you two objects with keys note and note2 on newData:

{ 
   note: {
      text: "test 1",
      badges: ["testing", "111"],
   },
   note2: {
      text: "test 2",
      badges: ["testing", "222"],
   },
}

Or you can just push the objects into an array of course.

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

Comments

0

Depending on how you want to use your grouping there are really 2 main options.

Single object

Each object will have its own unique key.

const note = {
  text: "test 1",
  badges: ["testing", "111"],
};
const note2 = {
  text: "test 2",
  badges: ["testing", "222"],
};

const newData = {
  note,
  note2
}

console.log("newData :", newData);

Array

Iterate through the item with ease.

const note = {
  text: "test 1",
  badges: ["testing", "111"],
};
const note2 = {
  text: "test 2",
  badges: ["testing", "222"],
};

const newData = [note, note2]

console.log("newData :", newData);

Comments

0

You can do something like this..

var note = {
  text: "test 1",
  badges: ["testing", "111"],
};
var note2 = {
  text: "test 2",
  badges: ["testing", "222"],
};

var newData = [note, note2]

console.log("newData :", newData);

Using this var newData = {...note, ...note2} is typically expanding object in object and since property name is same and object is treated as key value pair, you are getting last object as result.

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.