我想为名为gender的值添加一个新属性,默认值为" male"。完成添加属性的唯一方法是通过数组循环。或者是否有更有效的策略?
var data = [];
data.push({id: 1, values: {"age":33,"name":"Duke"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
var obj;
for obj in data {
obj.values.gender = "male";
}
所以data
将是
data = [
{id: 1, values: {"age":33,"name":"Duke","gender":"male"}},
{id: 1, values: {"age":34,"name":"Dave","gender":"male"}}
];
答案 0 :(得分:0)
我害怕说你无法避免for循环。但是,我已经为您创建了一个比较,您可以考虑性能。正如预期的那样,简单的for循环总是更快。看看:
var data = [];
data.push({id: 1, values: {"age":33,"name":"Duke"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
data.push({id: 2, values: {"age":34,"name":"Dave"}});
function foreachFn(d){
d.forEach(function(el){ el.values.gender='male'; });
return d;
}
function simpleLoopFn(d){
for (var i = 0;i<d.length;i++){
d[i].values.gender = "male";
}
}
function mappingData(d){
let newdata = d.map(function(el)
{
el.values.gender = 'male';
});
}
var t1 = 0, t2 =0;
let foreachData=data;
t1 = console.time('foreachFn')
foreachFn(foreachData);
t2 = console.timeEnd('foreachFn');
let simpleData= data;
t1 = console.time('simpleLoopFn')
simpleLoopFn(simpleData);
t2 = console.timeEnd('simpleLoopFn');
let mappedData = data;
t1 = console.time('mappingData')
mappingData(mappedData);
t2 = console.timeEnd('mappingData');
&#13;
答案 1 :(得分:0)
您可以尝试使用OOP Javascript并使用原型向该类型的所有对象添加属性:
function Person(age, name) {
this.age = age;
this.name = name;
}
var data = [];
data.push({id: 1, values: new Person(33, "Duke") });
data.push({id: 2, values: new Person(34, "Dave") });
Person.prototype.gender = 'male';
console.log(data[0].values.gender) // male
如果您知道要添加的属性并且它不是动态的,那么@ Tom的答案会更好。如果要分配给所有对象的属性在运行时之前是未知的,那么我的解决方案会更好。
答案 2 :(得分:-1)
有。您可以使用对象和构造函数为属性分配默认值。代码说的不仅仅是文字:
var Person = (function () {
function Person(age, name, gender) {
this.age = age;
this.name = name;
this.gender = gender ? gender : "male";
}
return Person;
}());
var data = [];
data.push({ id: 1, values: new Person(33, "Duke") });
data.push({ id: 2, values: new Person(34, "Dave") });
变为:
data = [
{
id: 1,
values: {
"age": 33,
"name": "Duke",
"gender":"male"
}
},
{
id: 2,
values: {
"age": 34,
"name": "Dave",
"gender":"male"
}
}
]
您甚至可以执行以下操作来更改男性以外的性别:
data.push({ id: 2, values: new Person(35, "Jessica", "female") });
的jsfiddle: https://jsfiddle.net/wtomcskr/1/