简体   繁体   中英

How to convert Object of Arrays to Objects

I have some data coming from the MVC controller in the below format:

{id: Array[3], city: Array[3]}

I wanted to convert that data into

[Object, Object, Object]

which will have the structure Object0{id, city} , Object1{id, city} , Object2{id, city}

I tried the below method but didnt work out

angular.forEach(data, function(){

    vm.Cities = {
        id :data.citiesIDs,
        city : data.citiesStr
    }

});

Can anyone please give me a hint as in where i am going wrong or what is the best way to achieve this. Thanks in advance.

You don't really need Angular for this, plain Javascript works just as well.

function transform(object) {
  var result = [];
  for (var i = 0; i < object.id.length; i++) {
    result.push({
      id: object.id[i],
      city: object.city[i]
    });
  }
  return result;
}

Then you can call your helper with your data:

var list = transform(data); // <-- list of (id,city) objects

Keep in mind the function assumes both of your id and city arrays are of the same length (which really wouldn't make sense if they weren't), BUT for the case they're not of the same length, you would want to make a minor change in your for loop:

var maxLen = Math.max(object.id.length, object.city.length);
for (var i = 0; i < maxLen; i++)

This is a simple JS operation and here is the demo

// Assuming obj is defined and both obj.id and obj.city are arrays

var obj = {
    id: [25, 82, 188, 141],
    city: ['Tokyo', 'Munich', 'Los Angeles', 'Sao Paolo'],
};

var max = Math.max(obj.id.length, obj.city.length);

var results = [];

for(var i = 0; i < max; i++) {
    var converted = {
        id: obj.id[i] ? obj.id[i] : null,
        city: obj.city[i] ? obj.city[i] : null
    };
    results.push(converted);
}

console.log('Coverted array', results);

Very simple example. Iterate over one of the arrays and grab from the other by index.

var cities = []
angular.forEach(data.id, function(id, index) {
    var city = {id: id, city: data.city[index]};
    cities.push(city);
});

Iterator can help you. eg:

var data = {id: [1,2], city: ['Curitiba','São Paulo']};
    var array = [];
    for(var prop in data){
        var length = data[prop].length;
        for(var z = 0; z < length; z++){
            if(!array.hasOwnProperty(z)){
                array[z] = {};
            }
            array[z][prop] = data[prop][z];
        }
    }
    console.log(array);// [Object{city:'Curitiba',id:1},Object{city:'São Paulo',id:2}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM