0

Tried to push new key and value but not working.Here given my code. Do not use {'id5':5} Because i am not trying to push object 1. Trying inside object 0

Demo: https://stackblitz.com/edit/js-1guupk

items = [{
  'id1': 1,
  'id2': 2,
  'id3': 3,
  'id4': 4
}];
items.push('id5': 5);
console.log(items);

Output should be:

console.log(items);

     0: Object
     id1: 1
     id2: 2
     id3: 3
     id4: 4
     id5: 5

4 Answers 4

4

var items = [{
    'id1': 1,
    'id2': 2,
    'id3': 3,
    'id4': 4
}];

// items[0] is an object
items[0].id5= 5;
console.log(items)

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

5 Comments

maybe you could add value to your answer by explaining why his way can't work
@jonatjano maybe you could read my answer and see the comment items[0] is an object
@8HoLoN I've seen it, but from the question, it's obvious OP need to be informed of the difference between arrays and object
How to convert array to object like ver test=[{'id;:1}] to test={'id;:1} ???\
Just i am asking you
2

You are trying to use .push() method on an object, that doesn't work. To get your result you have to add a property to an object.

For more info visit documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

items = [{
   'id1': 1, 
   'id2': 2, 
   'id3': 3, 
   'id4': 4
   }];
items[0]['id5'] =  5;
console.log(items);

1 Comment

maybe you could add value to your answer by explaining why his way can't work
0

It doesn't work for you because:

1- items is an array of objects when you push something to the array you add another value to the array example :

items.push("hello")

it results :

items = [{
  'id1': 1,
  'id2': 2,
  'id3': 3,
  'id4': 4
},
"hello"
];

2- your object is just the first element of the array (items[0])

items[0] == {
    'id1': 1,
    'id2': 2,
    'id3': 3,
    'id4': 4
}

3- you can access properties or add a new property to this object by a key this way:

items[0][key] = value; //key as a string

or

items[0].key = value;

it will override the value if the key already existe or add a new one otherwise.

Comments

0

You can perform this task by Destructuring the object

var items = [{
  'id1': 1,
  'id2': 2,
  'id3': 3,
  'id4': 4
}];

items = [{
  ...items[0],
  'id5': 5
}]

console.log(items)

MDN Doc

2 Comments

That did not work like you expected. Please always post a snippet
You mean items = [{ ...items[0], 'id5': 5 }]

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.