I'm trying to push an Object to an Array using the following command:
a = a.concat(b);
a = [];
b = {a: Object1, b: Object2 ....};
So I wan to have array a to be like a = [Object1, Object2...]
But the above statement results in:
a = [[Object1, Object2...][Object11, Object12...]];
How can I achieve this in JS?
4 Answers 4
If I ́m understanding what you want, you want just objects, not the keys. So, could be:
for( var key in b ){
var value = b[key];
a.push(value);
}
console.log(JSON.stringify(a));
Hope it helps...
Comments
You are concatenating two arrays with Array.concat() you need to use Array.push().
var a = [ObjectA];
var b = ObjectB;
a.push(b);
// a = [ObjectA, ObjectB];
4 Comments
b: var b = {a: ObjectA, b: ObjectB}b = {a:ObjectA, c: ObjectC, ...}a is an Array then try a.concat(Object.values(b)). This will concatenate the values from b to the a array.let a = [];
let b = {a:1, b:2, c:3};
for(obj in b){
let val = {};
val[obj] = b[obj];
a.push(val);
}
console.log(a);
Did you mean something like this ?
Comments
The
Object.values()method returns an array of a given object's own enumerable property values,
You could use the Object values method Object.values() , like :
Object.values(b);
Example :
var a = [];
var obj_1 = {'attr_1': 'val_1', 'attr_2': 'val_2'};
var obj_2 = {'attr_3': 'val_3', 'attr_4': 'val_4'};
var b = {'a': obj_1, 'b': obj_2};
a = Object.values(b);
console.log( a );
Hope this helps.
5 Comments
Object.values() is what you're searching for.Object.values() on rather than just: a.push(obj_1); a.push(obj_2);?...b = {a:ObjectA, c: ObjectC, ...}ObjectA and ObjectC ? give us a real case so we can understand more what you want to achieveObject.values(b) does the same thing that @Andre suggest in the accepted answer !!
a.push(b);...