我有一段JavaScript,如下所示
var set = [{
name: 'a',
property1: '',
property2: '',
},
{
name: 'b',
property1: '',
property2: '',
},
{
name: 'c',
property1: '',
property2: '',
}];
由于所有对象的property1
和property2
都为空,因此我想使它自动化,以便只需要跟踪名称。就像是:
namelist = ['a', 'b', 'c'];
magicFunction(namelist);
即magicFunction
可以返回set
我上面提到的。我对javascript非常陌生,如果您认为这对于stackoverflow来说太基本了,请给我几个关键字,以便我知道我应该搜索的内容。谢谢!
您可以使用地图
要获得set
从nameList
var namelist = ['a', 'b', 'c'];
var set = namelist.map(function(e) { return { name: e, property1: 0, property2: 0 }});
function magicFunction(arr) {
return arr.map(function(e) {
return {
name: e,
property1: 0,
property2: 0
}
});
}
var namelist = ['a', 'b', 'c'];
set = magicFunction(namelist);
console.log(set);
document.getElementById('output').innerHTML = JSON.stringify(set, 0, 2);
<pre id="output"></pre>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句