0
var arr= [{name:'xyz'},{name:'abc'}];

arr.forEach(function(a){
    a.age = 25;
    a.country = 'USA'
    a.technology = 'JavaScript'
});

How can I add these dynamic key-value pair with spread operator using ES6 syntax

2
  • 1
    Why do you want to use spread syntax ("Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.")? Commented Mar 23, 2018 at 12:17
  • why spread operator? Commented Mar 23, 2018 at 12:47

3 Answers 3

2
 arr = arr.map(prev => ({ ...prev, age: 25, country:"USA" }));
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, I want this with forEach loop
map is a foreach loop
@Sheena: No you don't.
@Luis felipe De jesus Munoz: I want to use forEach because I don't want to return a new array , I want to update the array – Sheena 8 mins ago
2

I don't think you can use spread syntax to modify an object, only to create a new object. If you want something that allows you to use a Javascript object literal to modify, use Object.assign()

arr.forEach(a => Object.assign(a, {
    age: 25,
    country: 'USA',
    technology: 'Javascript'
}));

1 Comment

@GerardoFurtado SO desperately needs a paren-matcher :)
0

Simply use this code:

var arr= [{name:'xyz'},{name:'abc'}];

var obj =  {
    age: 25,
    country: 'USA',
    technology: 'JavaScript'
};

arr.forEach(function(a){
    Object.assign(a, obj);
});

console.log(arr);

1 Comment

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

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.