简体   繁体   中英

Javascript convert objects to array

I have an array of arrays of objects like this:

var array = [
  [
    {
        name: 'a',
        value: 1,
        where: '1st array'
    },
    {
        name: 'b',
        value: 2,
        where: '1st array'
    }
  ],
  [
    {
        name: 'a',
        value: 1,
        where: '2nd array'
    },
    {
        name: 'b',
        value: 2,
        where: '2nd array'
    }
  ]
]

And I want to convert it to this:

[
  ['a', 1, '1st array'],
  ['b', 2, '1st array'],
  ['a', 1, '2nd array'],
  ['b', 2, '2nd array']
]

Can this be done using the array.map() method? I'm asking because there can be more than 1000 objects/array that will have to be converted and I think that a simple for inside for might not be efficient...

Use simple for loop for this with Object.values method, to get values as array

 var arr = [ [ { name: 'a', value: 1, where: '1st array' }, { name: 'b', value: 2, where: '1st array' } ], [ { name: 'a', value: 1, where: '2nd array' }, { name: 'b', value: 2, where: '2nd array' } ] ]; var newArr = []; for(let i in arr){ for(let j in arr[i]){ newArr.push(Object.values(arr[i][j])); } } console.log(newArr); 

You could use a destruction assignment for the inner array.

 var array = [[{ name: 'a', value: 1, where: '1st array' }, { name: 'b', value: 2, where: '1st array' }], [{ name: 'a', value: 1, where: '2nd array' }, { name: 'b', value: 2, where: '2nd array' }]], result = array.reduce( (r, a) => r.concat(a.map(({ name, value, where }) => ([name, value, where]))), [] ); console.log(result); 

Here is another way to achieve this. Get values like values=Object.values(array) and iterate over these values using simple for loop .

 var array = [ [ { name: 'a', value: 1, where: '1st array' }, { name: 'b', value: 2, where: '1st array' } ], [ { name: 'a', value: 1, where: '2nd array' }, { name: 'b', value: 2, where: '2nd array' } ] ] var outPut =[] var values=Object.values(array); //console.log(values); for(var i=0;i<values.length;i++){ for(var j=0;j<values[i].length;j++){ //console.log(values[i][j]); outPut.push(Object.values(values[i][j])); } } console.log(outPut); 

You need to do this in following way... you could improve it If you don't want to make it static , and you can make it dynamic. but it will be lengthy code ... :) var object1,object2;

array[0].forEach(function(element,index){
   obejct1[index] = Object.values(element);      

});

array[1].forEach(function(element,index){
   obejct2[index] = Object.values(element);      

});

object1[0].concat(object1[1],object2[0],object1[1]);

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