user3673623
user3673623

Reputation: 1925

javascript dynamically set value to object property

Is it possible to dynamically set value to javascript object. 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. 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. Any ideas?

Upvotes: 0

Views: 71

Answers (4)

Jaromanda X
Jaromanda X

Reputation: 1

a slight rewrite of your attempt

var object1 = {
    id: 1,
    colors: (function(){
        var ret = [];
        result.forEach(function(item) {
            ret.push(item.color);
        });
        return ret;
    }())
};

Upvotes: 0

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

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)
})

Upvotes: 0

Nikhil Batra
Nikhil Batra

Reputation: 3148

You can forEach loop to iterate the array result:

var object1 = {id:1, colors:[]};

result.forEach( function (item)
{
   object1.colors.push(item.color);
});

Upvotes: 0

Matthew King
Matthew King

Reputation: 1362

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);
}

Upvotes: 4

Related Questions