Reputation: 6082
I am storing a json object in json array and assign it to another main json object, but when I print the value of main json object it display 1. Below is the code.
var jsonMainObject= {};
var jsonArray= [];
for(var j=0;j<cu.receivedData.length;j++) {
jsonMainObject["company"] = jsonArray.push(cu.receivedData[j].company);
}
console.log(jsonMainObject)
Below is the output
{ company: 1 }
But it should show the array. when i print jsonArray it shows the array of object, but when I console the output of jsonMainObject it displays the above output.
Upvotes: 0
Views: 36
Reputation: 700592
There is no JSON at all here. JSON is a text format for representing data. What you have is a JavaScript object with a JavaScript array.
You are trying to put the array in the object at the same time as putting items in the array. The push
method doesn't return the array that it was called on, it returns the length of the array. The company
property will end up containing the length of the receivedData
array.
You can put the array in the object from start:
var arr = [];
var mainObject = { company: arr };
for(var j = 0; j < cu.receivedData.length; j++) {
arr.push(cu.receivedData[j].company);
}
console.log(mainObject);
Upvotes: 1
Reputation: 28339
The push
method returns the new length of the array. See documentation. I guess you should use:
jsonMainObject["company"].push(valueToPush)
or use concat
(documentation)
jsonMainObject["company"] = jsonMainObject["company"].concat(valueToConcat)
Upvotes: 2