简体   繁体   中英

How to push key and value into array in javascript

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

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

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);

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM