Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically set object properties in JavaScript?

Tags:

javascript

How can I use a dictionary of text names and values to set properties on an object? For example...

I need to populate this object:

item = {};

Using this collection of values (note everything is a string):

values = [
    { id: 1, name: "a", value: "true" },
    { id: 2, name: "b", value: "false" },
    { id: 3, name: "c", value: "100" },
    { id: 4, name: "d", value: "[email protected]" }
];

So that the original object looks like this:

item = {
    a: true,
    b: false,
    c: 100,
    d: '[email protected]'
}

Sorry for being so vague, but I'm not sure where to even start.

like image 232
G. Deward Avatar asked Sep 11 '26 11:09

G. Deward


1 Answers

You need to iterate over values, using the value of the name property of each item in that array as a key, and the value of the value property as the value:

var item = {}

values.forEach(function(i) {
  item[i.name] = i.value
})
like image 128
meagar Avatar answered Sep 13 '26 00:09

meagar