Javascript向数组中的所有对象添加相同的属性 [英] Javascript add same property to all objects in array

查看:549
本文介绍了Javascript向数组中的所有对象添加相同的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在没有角度或下划线的节点中工作,并且正在寻找有效的普通javascript答案(也许避免循环)。我有以下JSON对象数组:

I am working in node without angular or underscore and am looking for an efficient plain javascript answer (perhaps avoiding loops). I have the following array of JSON objects:

object = [
    {account:2423, user:1564},
    {account:1235, user:1564}
]

我想将以下内容添加到对象内的每个数组中:

I want to add the following to each array within the object:

username:"clientname" 

最后看起来像这样:

object = [
    {account:2423, user:1564, username:"clientname"},
    {account:1235, user:1564, username:"clientname"}
]

此问题要求避免循环。

推荐答案

您可以使用 Array.map 方法以获取结果。这是代码

You can use Array.map method to get the result. Here's code

var object = [
    {account:2423, user:1564},
    {account:1235, user:1564}
];

object.map(function(entry) {
    entry.username = "clientname";
    return entry;
});

这篇关于Javascript向数组中的所有对象添加相同的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆