Add a value to a JSON object

0

How can I add a string of values to a JSON object?

For example:

var a = 12;
var b = 3;

var obj = {
 c: 11,
 d:22
}
console.log(obj);

How can I apply to and b within my obj variable to become part of this JSON object?     

asked by anonymous 04.05.2016 / 20:45

2 answers

3

You can add a property to the obj object with the values of a and b , but note that doing so will give you a copy of the value, so modifications to the variable will not be reflected in obj and vice versa.

var a = 12;
var b = 3;

var obj = {
 c: 11,
 d:22
}

obj.a = a;
obj.b = b

console.log(obj);

a = 17;

//obj.a continua com o valor 12
console.log(obj);

If you need changes to the properties in the object to be reflected in the variables and vice versa, you should set a get and set to the obj property

var a = 12;
var b = 3;

var obj = {
 c: 11,
 d:22
}

Object.defineProperty(obj, "a", {
  get: function () { return a; },
  set: function (value) { a = value; },
  enumerable: true
});

Object.defineProperty(obj, "b", {
  get: function () { return b; },
  set: function (value) { b = value; },
  enumerable: true
});

console.log(JSON.stringify(obj));

a = 17;

console.log(JSON.stringify(obj));

obj.a = 12;

console.log(a);

Now if you have two objects, you can use the Object.assign method to move the two or more objects.

var base = { a: 12, b: 7 };
var objA = { c: 16, d: 4 };
var objB = { e: 13, f: 9 };

Object.assign(base, objA, objB);

console.log(base, objA, objB);

objA.c = 17;

//base.c continua com o valor 16
console.log(base, objA, objB);
    
04.05.2016 / 20:57
1
var a = 12;
var b = 3;

var obj = {
 c: 11,
 d:22
}

obj["a"] = a;

Here's an example: link

    
04.05.2016 / 20:54