Code On
Code On

Reputation: 233

set result value on JSON Array

so I have a var data with a result array JSON value like this:

[
   {"vehicle_id":"1", "model_name":"sedan"},
   {"vehicle_id":"2", "model_name":"elf"},
   {"vehicle_id":"3", "model_name":"truck"}
]

I want to set each value on new variable like this :

var newdata = [
    {
        text: Obj.model_name
        value: Obj.vehicle_id
    },
    {
        text: Obj.model_name
        value: Obj.vehicle_id
    },
    ......
];

How to set each value on the variable above ?

I already try this approach :

var newdata = [
    $.each(data, function(index, Obj){
       {
           text: Obj.model_name
           value: Obj.vehicle_id
       }
    })
];

But seems it's not working, can anyone have best practice of this case ?

Upvotes: 0

Views: 330

Answers (3)

嘿 嘿
嘿 嘿

Reputation: 64

Use 'map' instead of 'each'. Or use '$.each' like this:

var newdata = [];
$.each(data, function(index, Obj){
   newdata.push({
       text: Obj.model_name,
       value: Obj.vehicle_id
   })
});

Upvotes: 0

haim770
haim770

Reputation: 49095

Just use map():

var newData = data.map(function(item) {
    return {
         text: item.model_name,
         value: item.vehicle_id
    };
});

See MDN

Upvotes: 3

Felix Kling
Felix Kling

Reputation: 816364

Use .map:

var newData = data.map(function(obj) {
  return {
    text: obj.model_name,
    value: obj.vehicle_id,
  };
});

The problem with your code is that it is not doing anything. While $.each will iterate over the array, your function doesn't mutate the elements. It doesn't even create a new object, you are simply creating a block with two labels. You can think about it as being equivalent to

for (var i = 0; i < arr.length; i++) {
  arr[i].model_name;
  arr[i].vehicle_id;
}

i.e. you are only referencing the properties, but are not doing anything with those values.

Upvotes: 5

Related Questions