0

I would like to know if i can add an element in my array with a specific key with Spread Operator.

let foo = ['a','b','c'];
foo = [...foo,'d'];

In this case foo[3] would be d. But can i add d with a custon key in my foo array and then access with something like: foo['customKey']?

2
  • 5
    Why don't you use object rather than array? Commented Nov 4, 2019 at 13:35
  • 2
    But can i add d with a custon key in my foo array and then access with something like: foo['customKey'] no you can't. Elements in an array are accessed by the index. Commented Nov 4, 2019 at 13:36

2 Answers 2

1

You could take Object.assign instead of spreading an array, because this allows only to take iterable items for the new array.

let foo = ['a','b','c'];

foo = Object.assign([], [...foo], { customKey: 'd' });

console.log(foo);
console.log(foo.customKey);

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

Comments

0

Arrays are objects in JavaScript therefore they can have properties:

let foo = ['a','b','c'];
foo['customKey'] = 'd';
//Note using a for-in not for-of to iterate over enumerable & string properties
for (i in foo){
  console.log("The type of index is also a string: ", typeof i, i);
}

In fact when you access a array element using a number index, it is coerced into a string.

But with your use case, you should consider using an object:

let foo = {'foo' : ['a' , 'b','c']};
foo['customKey'] = 'd';
//Note using a for-in not for-of to iterate over enumerable & string properties
for (i in foo){
  console.log(foo[i]);
}

//Using object destructing
const d = {'anotherKey': 'e'};
const newFoo = {...foo, ...d};
console.log(newFoo);

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.