JSON Object Objects

0

I need to create a json object from scratch where each key has several values / values example:

 '{"name":["daniel","dias"],"morada":["joao","allen"]}'

For this I am executing this code several times, but the result is presented with numeric generated keys:

facetaPush - key name

response - array with desired values

valuesFacts - save json final object

var json_string = "";

json_string +='{\"'+facetaPush+'\":[' ;
for (var i = 0; i < response.length-1; i++) {
    json_string +='\"'+response[i]+'\",';
}
json_string +='\"'+response[response.length-1]+'\"]}';

var json_obj = JSON.parse( json_string );
valuesFacetas[facetaPush].push(json_obj);
alert("valores facetas: "+valuesFacetas[facetaPush][facetaPush]);
    
asked by anonymous 14.10.2016 / 17:45

4 answers

2

One quick way to resolve this is to use JSON.stringfy it accepts any value as an argument and serializes in JSON.

See the following example:

var obj = {
    name: ["daniel","dias"],
    morada: ["joao","allen"]
}

JSON.stringify(obj)
// Resultado: "{"name":["daniel","dias"],"morada":["joao","allen"]}"
    
14.10.2016 / 18:10
1

I think it's something like this you want:

function createMyObject(myKey, myCollection) {
   var myObj = new Object();
       myObj[myKey] = myCollection;
   return myObj;
}
var objName = createMyObject("name", ["daniel","dias"]);
var objMorada = createMyObject("morada", ["joao", "allen"]);

var all = createMyObject("myObjects", [objName, objMorada]);

console.log(objName, objMorada, all)
    
14.10.2016 / 19:01
0

If this is your default Objeto -> Array you can make a for to get the keys and another to go through the values of this array.

var json = {
  "name": ["daniel", "dias"],
  "morada": ["joao", "allen"]
};

console.log(json);

for (key in json) {
  console.log(key); // Pega chaves [name,morada]
  for (i = 0; i < json[key].length; i++) {
    console.log(json[key][i]); // [pega valores dos arrays dentro de name,morada]
  }
}
    
14.10.2016 / 18:14
0

The JSON is the String representation of the Javascript Object. It is easier to manipulate it as an object.

You can access a property of the object in several ways:

objeto.chave

or

objeto['chave']

Now we can change to a variable

var varChave = 'chave';
objeto[varChave]

I've done a few examples to see if you can find the best path in your case:

// suas variáveis
var facetaPush = 'name';
var response = ['daniel', 'dias'];

var objeto = {};
objeto[facetaPush] = response; // exemplo com variáveis
objeto['morada'] = ['joao', 'allen']; // exemplo estático
objeto.morada = ['joao', 'allen']; // exemplo estático

See how JSON would look:

var json = JSON.stringify(objeto);
// Resultado: "{"name":["daniel","dias"],"morada":["joao","allen"]}"
    
19.10.2016 / 21:22