0

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 ?

0

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

Just use map():

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

See MDN

Comments

0

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

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.