繁体   English   中英

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

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

ES6中是否有一种方法可以将对象数组中所有对象中的键值设置为新值。

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

例如,将每个项目的published值设置为true

您的示例中的数组只是对象的一维数组。

您可以使用forEach和lambda来执行您要求的操作:

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

使用map

arr = arr.map( s => (s.published = true, s) );

编辑

也不需要设置返回值

arr.map( s => (s.published = true, s) );

就足够了

演示版

 var arr = [{ title: 'my title', published: false }, { title: 'news', published: true } ]; arr.map(s => (s.published = true, s)); console.log(arr); 

我会使用循环。

arr表示您的对象数组

var result = []
for (var i = 0; i < arr.length; i++) {
  result.push([arr[i].title, arr[i].published])
}
console.log(result)

这将导致[['my Title', false], ['news', true]]

如果您不想循环,则可以使用index进行引用。

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

a[0].published= true;
a[1].published= true;

或循环

        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