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); } 
    0
      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
      • working fine var newArray = []; for(var i = 0; i < color_selected.length; i++) { newArray.push(color_selected[i].id); } this is also fine
        – sanu
        CommentedMay 12, 2017 at 17:28
      • @sanu javascript map is functional programming method. it's better if you can follow array methodCommentedMay 12, 2017 at 17:32
      • This is certainly a good solution, but it's worth noting that lambda expressions require ES6
        – Ben
        CommentedMay 12, 2017 at 17:38
      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
      • This is also a good solution, but is it worth bringing another library into your solution just to do this?
        – Ben
        CommentedMay 12, 2017 at 19:25
      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);

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.