[英]javascript dynamically set value to object property
Is it possible to dynamically set value to javascript object. 是否可以动态地将值设置为javascript对象。 For example i have the following array of objects:
例如,我有以下对象数组:
var result = [
{id: 1,color: ['black']},
{id: 1,color: ['white']},
{id: 1,color: ['green']}
];
And when creating another one i want to set all values color
from array result to the new object. 当创建另一个时,我想将所有值的
color
从数组结果设置为新对象。 Basically i want it to looks like this: 基本上我希望它看起来像这样:
{id:1, colors: ['black', 'white', 'green']}
I tried something like this: 我尝试过这样的事情:
var result = [
{id: 1,color: ['black']},
{id: 1,color: ['white']},
{id: 1,color: ['green']}
];
var object1 = {
id: 1,
colors: function(){
for(i = 1; i < result.length; i++) {
this.colors.push(result[i].color);
}
}
};
but it doesn't work and basically i understand why, i am just looking for workaround solution. 但它不起作用,基本上我理解为什么,我只是在寻找解决方法。 I am pretty new to javascript so i need some suggestions.
我对javascript很陌生,所以我需要一些建议。 Any ideas?
有任何想法吗?
Currently, you are setting colors to be a function, but you want colors to be an array. 当前,您正在将颜色设置为函数,但您希望颜色为数组。
One way to accomplish that is to do the following: 一种实现方法是执行以下操作:
var object1 = {
id: 1,
colors: []
};
for(var i = 0; i < result.length; i++) {
object1.colors.push(result[i].color);
}
You can forEach
loop to iterate the array result
: 您可以
forEach
循环来迭代数组result
:
var object1 = {id:1, colors:[]};
result.forEach( function (item)
{
object1.colors.push(item.color);
});
you can do it in this way. 您可以通过这种方式进行。
var result = [
{id: 1,color: ['black']},
{id: 1,color: ['white']},
{id: 1,color: ['green']}
];
var arrResult = {id:1,colors : []}
result.forEach(function(val,key){
arrResult.colors=arrResult.colors.concat(val.color)
})
a slight rewrite of your attempt 稍微重写您的尝试
var object1 = {
id: 1,
colors: (function(){
var ret = [];
result.forEach(function(item) {
ret.push(item.color);
});
return ret;
}())
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.