4

Is there a way to assign values to multiple keys of an object without repeating the object name?

For example: We have this object created:

var obj = {
  "a": 0,
  "b": 0,
  "c": 0,
  "d": 0
}

What i want now is to assign values to some or all keys of this object which is already created(you would normally do it like this):

obj["a"] = yourValue;
obj["c"] = yourValue;
obj["d"] = yourValue;

but without repeating the object name as i did above.
Would there be a way to do such thing?

2
  • is yourValue only a primitive value? Commented Nov 29, 2017 at 9:18
  • I don't think you can get away from repeating obj... Commented Nov 29, 2017 at 9:20

6 Answers 6

6

You could use Object.assign and map the wanted keys with the values as object for an update with the wanted value.

var object = { a: 0, b: 0, c: 0, d: 0 },
    value = 42,
    keys = ['a', 'c', 'd'];

Object.assign(object, ...keys.map(k => ({ [k]: value })));

console.log(object);

ES5

var object = { a: 0, b: 0, c: 0, d: 0 },
    value = 42,
    keys = ['a', 'c', 'd'];

keys.forEach(function (k) {
    object[k] = value;
});

console.log(object);

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

Comments

3

but without repeating the object name as i did above.

Object assign might come handy here

Object.assign(obj, { a: 0,b:0,c:0 });

var obj = {
  "a": 0,
  "b": 0,
  "c": 0,
  "d": 0
}
Object.assign(obj, { a:1,b:0,c:1 });
console.log(obj)

Comments

1
var obj = {
  "a": 0,
  "b": 0,
  "c": 0,
  "d": 0
};
yourvalue = 'test'
for(key in obj){
    obj[key] = yourvalue

}

A for-in loop will work for you. It loops trough all key entries and allows you to assign a value to it.

3 Comments

This assigns all values to youvalue.
Isn't this what he wanted? He used 'yourValue' in his example as well.
What i want now is to assign values to some or all keys of this object which is already created
0

You can't go without iterating through the keys

var obj = {
  "a": 0,
  "b": 0,
  "c": 0,
  "d": 0
}

Object.keys(obj).forEach(k => {
  obj[k] = yourValue;
});

Comments

0

may be with will help you, but

Use of the with statement is not recommended

Comments

0

You could create an array with the key values and then use a for loop.

var obj = {
  "a": 0,
  "b": 0,
  "c": 0,
  "d": 0
}
var arr = ["a", "b", "c", "d"];
for(var i = 0; i<arr.length; i++){
  obj[arr[i]] = yourValue;
}

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.