0

I currently have data in the following format:

var anArray = [
  obj1: {
    key1: data1
  },
  obj2: {
    key2: data2
  },
];

I would like the data to instead be in the following format:

var array2 = [data1, data2];

for some reason, I cannot figure out a concise way to to this. I know it could be done with a forEach loop that iterates over each object and pushes it onto a new array, but I would prefer to be more elegant (and shorter if possible) than that.

jimo337
  • 69
  • 11
  • 2
    That is not a valid Javascript object literal. Please provide your object/arrays in valid notation. – trincot Feb 21 '17 at 22:10
  • please add what kind of date you have. – Nina Scholz Feb 21 '17 at 22:19
  • Possible duplicate of [From an array of objects, extract value of a property as array](http://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – Bulent Vural Feb 21 '17 at 22:19
  • After this edit, it is still invalid. After a `[` you cannot have a property name with a colon following it. First check in your code that it does not produce a syntax error, before posting. – trincot Feb 21 '17 at 22:23

3 Answers3

1

const anArray = {
  obj1: {
    key1: "A"
  },
  obj2: {
    key2: "B"
  },
};

const result = Object.keys(anArray).map(key => {
  const obj = anArray[key];
  return Object.keys(obj).map(key => obj[key])[0];
});

console.log(result);
0

Try with:

const arr1 = [
 {key1:'value1'},
        {key2:'value2'}  
]

const res = arr1.map(obj => {
           return Object.keys(obj).map(val => obj[val])
           }).reduce((acc,v) => { 
           return acc.concat(v);
           },[]);

console.log(res);

update
But if you have the following form:

var anArray = [
  obj1: {
    key1: data1
  },
  obj2: {
    key2: data2
  },
];

It's better to apply a recursive function, as follow:

const arr1 = [
 {
   obj1:{key1:'value1',key3:'value3'}
  },
 {
   obj2:{key2:'value2'}
  }
]

const getValuesFromObj = (obj) => {
 if(typeof obj === 'string')
   return obj;
    
 return Object.keys(obj).map(key => {
       return getValuesFromObj(obj[key]);
        }).reduce((acc,v) => {
   return acc.concat(v);   
  },[]);
}



const r2 = getValuesFromObj(arr1);
console.log(r2);
Hosar
  • 5,163
  • 3
  • 26
  • 39
0

Given that anArray is actually properly structured to be valid, then you could do the following: Note that in this case anArray isn't an actual array but rather a object literal

var anArray = {
    obj1: {
        key1: "data1"
    },
    obj2: {
        key2: "data2"
    },
};

var array2 = []
for(i in anArray){
    for(j in anArray[i]){
        array2.push(anArray[i][j])
    }
}
console.log(array2)

https://jsfiddle.net/wh4r0w5s/

Mathias W
  • 1,433
  • 12
  • 16