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
?
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);
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);
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]]
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;
}
您可以将map
功能与点差运算符一起使用
let array = [ { title: 'my title', published: false }, { title: 'news', published: true } ]
array = array.map(t => t.published !== true ? { ...t, published: true } : t)
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.