Code On Code On - 5 months ago 9
jQuery Question

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 ?

Answer

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.

Comments