How to create an JSON array like this in javascript - javascript

What is the best way to create an array that looks like the following:
[
{
"id":"1",
"value": true
},
{
"id":"3",
"value": false
},
{
"id":"5",
"value": true
},
{
"id":"6",
"value": false
},
{
"id":"9",
"value": true
},
]
My code:
//add to array
thing = {
"id" : 1,
"value" : "true"
};
thingArray.push(thing);
It does not seem to be properly formatted when I put the output in a JSON validator.

As I commented further up, make sure you're actually serializing it to JSON at some point. In your code example you're simply working with a JavaScript object, which isn't the same thing as JSON. Here's an example:
// start with a regular JavaScript array
var array = [];
// push some regular JavaScript objects to it
array.push({
id: 1,
value: true
});
array.push({
id: 2,
value: false
});
// serialize your JavaScript array into actual JSON
var json = JSON.stringify(array);
// do whatever you want with it...
console.log(json);
Here's a JSBin example.

Your code is fine. Here's some more code to get you started:
var arr = [];
arr.push({"id": 1, "value": "true"});
arr.push({"id": 2, "value": "false"});
console.dir(arr);
http://jsfiddle.net/gg014w0h/
You can run that fiddle and then check your console output. You'll see the contents of the array pretty clearly.

JSON validators will not like the trailing comma of the array. There is a difference between console.log(array) and console.log(JSON.stringify(array)). You may want to use the latter.
Also note that booleans are allowed in JSON:
"value": "true",
"value": true
Those are both valid and they mean different things.

Related

How access nested JSON node after converting from SOAP?

Using node.js(javascript) how do I access the GetDataResult node in this JSON data that has been converted from SOAP data.
{
"s:Envelope": {
"$": {
"xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
},
"s:Body": [{
"GetDataResponse": [{
"$": {
"xmlns": "http://tempuri.org/"
},
"GetDataResult": ["You entered: TEST"]
}]
}]
}
}
Test using nodejs interactive mode :
$ node
> var x = {
... "s:Envelope": {
..... "$": {
....... "xmlns:s": "http://schemas.xmlsoap.org/soap/envelope/"
....... },
..... "s:Body": [{
....... "GetDataResponse": [{
......... "$": {
........... "xmlns": "http://tempuri.org/"
........... },
......... "GetDataResult": ["You entered: TEST"]
......... }]
....... }]
..... }
... }
undefined
> console.log(x["s:Envelope"]["s:Body"][0]["GetDataResponse"][0]["GetDataResult"][0])
Output :
'You entered: TEST'
Explanations :
I try to elaborate a bit from comments below. There is no container, I try to explain :
You have to think json like what it is : an object or a data structure.
In python, we would say it's a dict, in perl a hash table etc... Globally, it's all about associative array
So when you see in JSON :
"key" : { "value" }
it's an associative array
If instead you see
"key": [
{ "key1": "foo" },
{ "key2": "bar" },
{ "key3": "base" }
]
It's an array of hashes or array of associative arrays.
When you access a simple associative array without spaces or odd characters, you can (in js do :
variable.key
In your case, you have odd character : in the key name, so x.s:Envelope wouldn't work. Instead we write: x['s:Envelope'].
And as far as you have arrays of associative arrays inside [], you have to tell js which array number you need to fetch. It's arrays with only one associative array, so it's simple, we go deeper in the data structure by passing array number, that's what we've done with
x['s:Envelope']["s:Body"][0]
^
|

Merge and array from within an object to every key form object

So, I have an object as follows:
custom_fields:{
21:{
edit:true
required:true
show:true
}
}
Which in my angular controller is stored here: $scope.page.custom_fields
Within this object I have another one, like this:
custom_fields:{
21:{
edit:true
required:true
show:true
}
22:{
edit:true
required:true
show:true
}
data:[
0:{
display_name:"Text"
id:21
name:"Text"
value:[
0:{"TextHere"}
]
}
1:{
display_name:"Text"
id:22
name:"Text"
value:[
0:{"TextHere"}
]
}
]
}
This one is stored like this: $scope.page.custom_fields.data = response.data.custom_fields;
As you can see the first one is an object of objects while the second one is an array of objects. I don't know why they ended up like this, but I would need to assign the first key in data to the first key in custom fields, so they would look like this in the end:
custom_fields:{
21:{
edit:true
required:true
show:true
display_name:"Text2"
id:21
name:"Text"
value:[
0:{"TextHere"}
]
}
}
I should do this in the angular controller. As you can see every id from data corresponds to the key in custom_fields (in this case 21:{} and data[0:{id:21}])
But they are being put in order by a foreach in php so there is no need to make a foreach in js too, I only have to assign in order every key from custom_fields.data to every key from custom_fields
But how can I do this?
data[0:{id:21}]
No, this is not possible.
Please refer link
numeric-type-as-an-object-key
It will be very difficult to use the $scope.page.custom_fields.21 later in your code. So better use it as array format instead of object. Following code will help you parse it in array of objects of custom fields.
angular.forEach($scope.custom_fields.data, function(value, idx){ // may be $scope.custom_fields.custom_fields.data as per your code. Please correct accordingly.
if($scope.custom_fields[value.id]){
angular.merge($scope.custom_fields.data[idx], $scope.custom_fields[value.id]);
delete($scope.custom_fields[value.id]);
}
});
$scope.custom_fields = $scope.custom_fields.data;
console.log($scope.custom_fields);
let custom_fields = {
"21": {
"edit": true,
"required": true,
"show": true
},
"22": {
"edit": true,
"required": true,
"show": true
},
"data": [{
"display_name": "Text",
"id": 21,
"name": "Text",
"value": ["TextHere"]
}, {
"display_name": "Text",
"id": 22,
"name": "Text",
"value": ["TextHere"]
}]
};
custom_fields.data.forEach(function(item) {
let obj = custom_fields[item.id];
for (let attr in item)
obj[attr] = item[attr];
});
//Remove the data property
delete custom_fields.data;
console.log(custom_fields);
As I said in comment, I think you need a loop to asign each custom fields
var i = 0;
for (var key in custom_fields) {
if (custom_fields.hasOwnProperty(key)) {
// only if you are sure that data is ordered, else must be filter data by custom_fields[key].id
custom_fields[key].display_name = data[i].display_name;
custom_fields[key].name = data[i].name;
custom_fields[key].value = data[i].value;
i++;
}
}
I hope this will help you

About C3.js chart data split

Since i am not familiar with C3.js library, i am bit confuse when i tried to split the Array data.
For instant i have some array value from a json.
var jsondata=[[123],[45],[56],[22]];
var jsondataName=[["apple"],["orange"],["banana"],["pear"]];
I tried to pass the first array jsondata into the chart but these values go into the same column which is not something i would like to see.
I want these array value become independent data and push the name into it
Please see the demo i made :
http://jsfiddle.net/q8h39/92/
And the result i want should looks like
Update the json data format :
"Name": apple,
"data": {
"value": 1434,
}
"Name": banana,
"data": {
"value": 342,
}
}
}
You can set the JSON object to data.json and then set data.keys.value to an array of values in that JSON:
var jsondata = [{
"Name": "apple",
"data": {
"value": 1434,
},
}, {
"Name": "banana",
"data": {
"value": 342,
}
}];
var chart = c3.generate({
data: {
json: jsondata,
keys: {
value: [
"name", "data.value"
]
},
type: "scatter"
//hide: true
}
});
http://jsfiddle.net/aendrew/mz9ccbrc/
n.b., You need C3 v0.4.11 for this (the dot syntax for keys.value was just added), and your JSON object needs to be an array (currently it's not valid).
If you want to convert the two arrays from your initial question to that format of JSON, try this:
d3.zip(jsondataName, jsondata)
.map((d) => Object({name: d[0][0], data: { value: d[1][0] } }));

How to parse a JSON array string in JavaScript?

I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']

push syntax in Javascript for an array within an array

"elements": [
{
"values": [
{
"value": 70
}
],
"dot-style": {
"dot-size": 2,
"halo-size": 2,
"type": "solid-dot"
},
"on-show": {
"type": ""
},
"font-size": 15,
"loop": false,
"type": "line",
"tip": "#val#%"
}
]
In the above array example I need to add data to values array which is part of elements array dynamically. How do I do it using JavaScript push method?
As you will see, it's much easier to conceptualise your code if it is formatted well. Tools like jsBeautifier can help with this task.
First, it's clear that elements is part of a JS object. We'll call it foo, but you'll have to change this to the correct name in your code.
foo.elements[0].values.push({
value: 'some value'
});
This will add a new object to the values array.
elements[0].values.push({"value": new_value});
if the above is named var obj,
obj['elements'][0]['values'].push(someValue);
Presuming elements is part of an object called myObj for the example below, you could use either syntax.
myObj["elements"][0]["values"].push({ value: "my new value" });
or
myObj.elements[0].values.push({ value: "my new value" });

Categories