Reputation: 24061
Is there a way in ES6, to set value of a key in all objects, in an array of objects to a new value.
[
{title: 'my title', published: false},
{title: 'news', published: true},
...
]
For example, setting every item published
value to true
?
Upvotes: 1
Views: 862
Reputation: 3272
You can use the map
function with spread operator
let array = [
{ title: 'my title', published: false },
{ title: 'news', published: true }
]
array = array.map(t => t.published !== true ? { ...t, published: true } : t)
Upvotes: 0
Reputation: 5340
If you don't want a loop you can refer with index.
a = [
{title: 'my title', published: false},
{title: 'news', published: true}
]
a[0].published= true;
a[1].published= true;
or loop it
for (val in a) {
a[val].published = true;
}
Upvotes: 0
Reputation: 68383
Use map
arr = arr.map( s => (s.published = true, s) );
Edit
No need to set the return value either, just
arr.map( s => (s.published = true, s) );
would suffice
Demo
var arr = [{
title: 'my title',
published: false
},
{
title: 'news',
published: true
}
];
arr.map(s => (s.published = true, s));
console.log(arr);
Upvotes: 1
Reputation: 5629
I'd use a loop.
arr
represents your array of objects
var result = []
for (var i = 0; i < arr.length; i++) {
result.push([arr[i].title, arr[i].published])
}
console.log(result)
this will result in [['my Title', false], ['news', true]]
Upvotes: 1
Reputation: 142
The array in your example is just a one-dimensional array of objects.
You can do what you asked with forEach
and a lambda:
array.forEach(element => element.published = true);
Upvotes: 3