0

I have two array with custom key but when i want to merge them JavaScript return emtpy array.

let x = [];
x['a'] = 1;

let y = [];
y['b'] = 2;

console.log(x.concat(y));
console.log([...x, ...y]);

There is any way to use JavaScript function two merge them or i have to use for and iterate all items??

2
  • 1
    let y = []; y['b'] = 2 results in an array with a property with the key 'b' and the value 2. concat and ... only consider properties with integral keys. Please explain what you are trying to accomplish as I doubt you are using the correct data structures. Commented Jul 16, 2020 at 5:18
  • 1
    @AluanHaddad Thank you for your comment. I understand that i should use Object for my case when i read your notice. Commented Jul 16, 2020 at 5:37

3 Answers 3

4

Since you are using arrays like Object, use Object.keys. (Object.values and Object.entries)

let x = [];
x['a'] = 1;

let y = [];
y['b'] = 2;

console.log(x.concat(y));
console.log([...x, ...y]);

console.log([...Object.keys(x), ...Object.keys(y)]);
console.log([...Object.values(x), ...Object.values(y)]);

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

Comments

2

Here you use string value as an array key. Which is not allowed in JavaScript. If you want string as a key you need to use 'object' instead of array.

1 Comment

Not to be pedantic, but it absolutely is allowed they just aren't considered elements of the array, rather they are treated like length. It is usually best avoided however.
0

If you want to merge this with using object try this:

let x = [{}];
x[0]['a'] = 1;

let y = [{}];
y[0]['b'] = 2;

console.log(x.concat(y));

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.