2

I have array of objects :

array = [
  {name: 'name'},
  {name: 'name'},
  {name: 'name'},
  {name: 'name'},
]

I want to add key: '123' to each of them so it would be :

array = [
  {name: 'name', key: '123'},
  {name: 'name', key: '123'},
  {name: 'name', key: '123'},
  {name: 'name', key: '123'},
]

What I've tryed :

checked = false;
     this.editObj.forEach(item => item.push(this.checked))

ERROR : item.push is not a function.

But it isn't working. How to do it in the right way ?

1
  • You want to modify the object within the array so you need to use item["key"] = "123" Commented Oct 30, 2018 at 9:46

5 Answers 5

3
const arr = [
  {name: 'name'},
  {name: 'name'},
  {name: 'name'},
  {name: 'name'},
]

const arr2 = arr.map(x => ({...x , key: '123'}));
Sign up to request clarification or add additional context in comments.

1 Comment

Mixing ES5 var with ES6 ... (spread operator) is uncanny. Please use const
2

You can try with creating custom dictionary

array = [
{name: 'name'},
{name: 'name'},
{name: 'name'},
{name: 'name'},
]

var dict = []; // create an empty dictionary
for (i = 0; i < array.length; i++) { 

  dict.push({
    key:   "123",
    value: array[i].name
  });
  

}
  console.log(dict);

Comments

2

you should do :

this.editObj.forEach(item => item["key"]= "123");
console.log(this.editObj);

1 Comment

this is returning an error :) Uncaught SyntaxError: missing ) after argument list
1

Your code is not working because you use .push() on object, not on array. Try this:

this.editObj.forEach(item => item["key"] = this.checked);

3 Comments

Look at no-return-assign rule.
@GrégoryNEUT I know this rule, but it's a shorthand 1-liner
what about this.editObj.forEach(item => (item["key"] = this.checked;));
1

In everything except IE11

Creating a new array

const array = [{
    name: 'name',
  },
  {
    name: 'name',
  },
  {
    name: 'name',
  },
  {
    name: 'name',
  },
];

console.log(array.map(x => ({
  ...x,

  key: '123',
})));

Updating existing array

const array = [{
    name: 'name',
  },
  {
    name: 'name',
  },
  {
    name: 'name',
  },
  {
    name: 'name',
  },
];

array.forEach((x) => {
  x.key = '123';
});

console.log(array);


In IE11

var array = [{
    name: 'name',
  },
  {
    name: 'name',
  },
  {
    name: 'name',
  },
  {
    name: 'name',
  },
];

for (var i = 0; i < array.length; i += 1) {
  array[i].key = '123';
}

console.log(array);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.