最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to push key and value into array in javascript - Stack Overflow

programmeradmin3浏览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:

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

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./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
Share Improve this question edited Jul 23, 2020 at 8:59 mplungjan 179k28 gold badges182 silver badges240 bronze badges asked Jul 23, 2020 at 8:57 MakizhMakizh 1892 gold badges9 silver badges19 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

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

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.

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

发布评论

评论列表(0)

  1. 暂无评论