0

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?

asked Aug 15, 2017 at 16:13
1
  • 2
    a.push(b);... Commented Aug 15, 2017 at 16:15

4 Answers 4

1

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...

answered Aug 15, 2017 at 16:20
Sign up to request clarification or add additional context in comments.

Comments

0

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];
answered Aug 15, 2017 at 16:15

4 Comments

var b = {ObjectA, ObjectB}
That makes no sense in JS unless those objects are property values of b: var b = {a: ObjectA, b: ObjectB}
yeah the value is like this b = {a:ObjectA, c: ObjectC, ...}
If a is an Array then try a.concat(Object.values(b)). This will concatenate the values from b to the a array.
0

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 ?

answered Aug 15, 2017 at 16:17

Comments

0

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.

answered Aug 15, 2017 at 16:15

5 Comments

Check my update, I got you, Object.values() is what you're searching for.
Is it really more beneficial in this case to create a third object to call Object.values() on rather than just: a.push(obj_1); a.push(obj_2);?...
Same result. The value of b is like: b = {a:ObjectA, c: ObjectC, ...}
What you mean by ObjectA and ObjectC ? give us a real case so we can understand more what you want to achieve
@user1012181 the Object.values(b) does the same thing that @Andre suggest in the accepted answer !!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.