How to concatenate variable with empty object (between keys)?

Asked

Viewed 130 times

3

To add value in arrays (between brackets []) use $objeto.push('novoValor');

How do I add values in variables between keys (empty object)?

Example :

$objeto = {} add $objeto = {"conteudo":"dado"}

2 answers

5


$objeto = {}; 
$objeto.conteudo = [];

for(var i = 1; i < 4; i++) {
  $objeto.conteudo.push({"dado":"" + i});
}
console.log($objeto.conteudo);

$objeto = {};
$objeto.conteudo = "dado";
alert($objeto.conteudo);

Javascript is a dynamic language, meaning you can set new properties for an object at any point of execution.

Therefore, to add the value to which it refers, simply assign directly to the property:

$objeto.conteudo = "dado";
  • 1

    I know you already answered and I appreciate it. But I wanted to concatenate recursively. Go inserting the values forming a JSON. I made the following version of the code: $object = {}; $object.content = $object.content+'{"given":"1"}'; $object.content = $object.content+'{"given":"2"}'; $object.content = $object.content+'{"given":"3"}'; console.log($object.content); The result was: Undefined{"given":"1"}{"given":"2"}{"given":"3"}

  • I edited my answer with the cited example. Is that what I was thinking? In my understanding, you want an array "content" within your object.

  • In case that’s the case, I suggest you edit the question so that it is clearer to whom to consult later. I also edit my answer to stay aligned.

  • That’s right. I made the question clearer. Thanks again!

4

If you already have a variable with an empty object you can simply do

obj.propriedade = valor;

If you’re starting everything you can do:

var obj = {propriedade: valor};

If a(s) property(s) is dynamic, i.e., the name of the property/key is inside a variable, then you can do so:

var prop = 'minhaPropriedade';
var obj = {[prop]: 12345};
console.log(obj.minhaPropriedade); // dá 12345

Browser other questions tagged

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