0

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?

1
  • All the answers make an assumption that you only have one id value (i.e. 1). Is that what you want? Will there be any objects with an id of 2 or with different ids? Commented Jul 6, 2015 at 7:12

4 Answers 4

4

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can forEach loop to iterate the array result:

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

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

Comments

0

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

Comments

0

a slight rewrite of your attempt

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.