Add a value to a JSON object

Asked

Viewed 10,008 times

0

How could I add a value chain to an object JSON?

For example:

var a = 12;
var b = 3;

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

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

2 answers

4


you can add a property to the object obj with the values of a and b, but note that in doing so, you will be assigning a copy of the value, so modifications to the variable will not be reflected in the 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 in the properties of the object to be reflected in the variables and vice versa, you must define a get and set for the property of obj

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 method Object.assign to aid 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);

  • then if I have n values, I would have to perform a repeat loop to set each value?

  • 1

    yes, you will have to do this for each variable. but there is a way of meclar objects using the Object.assign, I added an example to the answer.

  • You’re fucking man, thank you so much for the help

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.