admin管理员组

文章数量:1302292

I have following response say from an API

[{name : Taj Mahal, lat : 111 , lng : 222},
{name : Agra Fort, lat : 333 , lng : 444},
{name : Red Fort, lat : 555 , lng : 666}]

I wish to populate an array like this

var coordinates = [[Taj Mahal, 111, 222],
    [Agra Fort, 333, 444],
    [Red Fort, 555, 666]]

I have following response say from an API

[{name : Taj Mahal, lat : 111 , lng : 222},
{name : Agra Fort, lat : 333 , lng : 444},
{name : Red Fort, lat : 555 , lng : 666}]

I wish to populate an array like this

var coordinates = [[Taj Mahal, 111, 222],
    [Agra Fort, 333, 444],
    [Red Fort, 555, 666]]
Share edited Feb 15, 2017 at 12:05 Jite 5,8472 gold badges27 silver badges39 bronze badges asked Feb 15, 2017 at 12:03 samsam 6982 gold badges13 silver badges36 bronze badges 5
  • 2 Whats the problem – M A SIDDIQUI Commented Feb 15, 2017 at 12:04
  • You want solution in JavaScript/PHP? – Satpal Commented Feb 15, 2017 at 12:04
  • 3 This is a fairly simple mapping. Show us what you have tried, this isn't a free code writing service – charlietfl Commented Feb 15, 2017 at 12:05
  • @Satpal in javascript but i thought logic would be the same in php so i tagged it as well – sam Commented Feb 15, 2017 at 12:05
  • iterate through Object.keys(<each_nested_object>) – RomanPerekhrest Commented Feb 15, 2017 at 12:06
Add a ment  | 

3 Answers 3

Reset to default 6

You can use map to achieve this

var arr = [{ name: 'Taj Mahal', lat: 111, lng: 222 },
            { name: 'Agra Fort', lat: 333, lng: 444 },
            { name: 'Red Fort', lat: 555, lng: 666 }];


var newArr = arr.map(function (item) {
  return [item.name, item.lat, item.lng];
});
console.log(newArr);

With uping ES7, you could use Object.values.

var data = [{ name: 'Taj Mahal', lat: 111, lng: 222 }, { name: 'Agra Fort', lat: 333, lng: 444 }, { name: 'Red Fort', lat: 555, lng: 666 }];

console.log(data.map(o => Object.values(o)));

ES5

var data = [{ name: 'Taj Mahal', lat: 111, lng: 222 }, { name: 'Agra Fort', lat: 333, lng: 444 }, { name: 'Red Fort', lat: 555, lng: 666 }];

console.log(data.map(function (o) {
    return Object.keys(o).map(function (k) {
        return o[k];
    });
}));

You can simply map this by using Object.values(obj)

var coordinates = response.map(x => Object.values(x));

本文标签: Creating array inside an array in javascriptStack Overflow