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.

4
  • 2
    That is not a valid Javascript object literal. Please provide your object/arrays in valid notation. Commented Feb 21, 2017 at 22:10
  • please add what kind of date you have. Commented Feb 21, 2017 at 22:19
  • Possible duplicate of From an array of objects, extract value of a property as array Commented Feb 21, 2017 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. Commented Feb 21, 2017 at 22:23

3 Answers 3

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

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

Comments

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/

Comments

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

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.