简体   繁体   English

在ES6中的对象数组中设置键的值?

[英]Set value of a key in an array of objects in ES6?

Is there a way in ES6, to set value of a key in all objects, in an array of objects to a new value. ES6中是否有一种方法可以将对象数组中所有对象中的键值设置为新值。

[
    {title: 'my title', published: false},
    {title: 'news', published: true}, 
    ...
]

For example, setting every item published value to true ? 例如,将每个项目的published值设置为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: 您可以使用forEach和lambda来执行您要求的操作:

array.forEach(element => element.published = true);

Use map 使用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 arr表示您的对象数组

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]] 这将导致[['my Title', false], ['news', true]]

If you don't want a loop you can refer with index. 如果您不想循环,则可以使用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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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