2

I want to update my object values with some predefined value like 5.

Here is my object,

let data = {"a":1,"b":2,"c":3,"d":5}

Expected Output;

let data = {"a":5,"b":10,"c":15,"d":25}

Here is my attempt:

Object.keys(data).map(key => data[key] *= 5 )
2
  • 2
    The posted question does not appear to include any attempt at all to solve the problem. StackOverflow expects you to try to solve your own problem first, as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific roadblock you're running into a minimal reproducible example. For more information, please see How to Ask and take the tour. Commented Dec 3, 2018 at 7:06
  • @CertainPerformance please see updated questation Commented Dec 3, 2018 at 7:11

3 Answers 3

4

Just loop through all the new object's key and update it to existing object.

var obj = {"a":1,"b":2,"c":3,"d":5,"f":9,"g":11,"h":21}

var newObj = {"a":5,"b":10,"d":20,"h":25}

let keys = Object.keys(newObj)

keys.map(x=>{
  obj[x] =  newObj[x]
})

console.log(obj)

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

Comments

3

Multiply that values with 5:

let data = {"a":1,"b":2,"c":3,"d":5};
Object.keys(data).forEach(key => data[key] *= 5);
console.log(data);

Using Object.Entries()

let data = {"a":1,"b":2,"c":3,"d":5};
Object.entries(data).forEach(([key, val]) => data[key] = val*5);
console.log(data);

Comments

1

Try with Object.entries():

The Object.entries() method returns an array of a given object's own enumerable property [key, value] pairs, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well) .

let data = {"a":1,"b":2,"c":3,"d":5}
data = Object.entries(data).map(k => ({[k[0]]: k[1] * 5}))

console.log(data)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.