0

Hi I have json return object like this

color_selected = [
                { id: 4}, 
                { id: 3} 
    ];

how do I convert it to

color_selected = [4,3]

thank you for your any help and suggestions

4 Answers 4

3

You could iterate through it like this:

var newArray = [];
for(var i = 0; i < color_selected.length; i++) {
    newArray.push(color_selected[i].id);
}
Sign up to request clarification or add additional context in comments.

Comments

2

you can use javascript map function for that

var newArray = color_selected.map(o=> o.id)

var color_selected = [
                { id: 4}, 
                { id: 3} 
    ];
 var newArray = color_selected.map(o=> o.id)
 console.log(newArray)

3 Comments

working fine var newArray = []; for(var i = 0; i < color_selected.length; i++) { newArray.push(color_selected[i].id); } this is also fine
@sanu javascript map is functional programming method. it's better if you can follow array method
This is certainly a good solution, but it's worth noting that lambda expressions require ES6
1
color_selected = [
            { id: 4}, 
            { id: 3} 
];

You can use lodash

// in 3.10.1

_.pluck(color_selected, 'id'); // → [4, 3]
_.map(color_selected, 'id'); // → [4, 3]

// in 4.0.0

_.map(color_selected, 'id'); // → [4, 3]

1 Comment

This is also a good solution, but is it worth bringing another library into your solution just to do this?
0

Use Array.map() method with ES6 Arrow operator.

var color_selected = [
                { id: 4}, 
                { id: 3} 
    ];
    
color_selected = color_selected.map(item => {return item.id });

console.log(color_selected);

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.