"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" });
Related
I want to use this data (below) as a data source for a d3.js program:
{
"component": {
"name1": {
"graphname": {
"title": "foo",
"data": [
{"data": "DATE IN ISOFORMAT", "value": 5},
{"data": "DATE IN ISOFORMAT", "value": 10}
]
}
},
"name2": {
"graphname": {
"title": "foo",
"data": [
{"data": "DATE IN ISOFORMAT", "value": 5},
{"data": "DATE IN ISOFORMAT", "value": 10}
]
}
}
}
"component2": {...
}
D3 accepts only array data? How i can manipulate it to work?
I want to graph for all component any "graphname" aggregated by "name"
Any tips?
D3 does not just accept arrays as data sources, but for looping purposes, arrays are much more convenient than JavaScript objects ("dicts"). There is a very easy way to convert objects to arrays, though. If your object above were called d, then its corresponding array can be created with:
var dlist = d3.entries(d);
Now dlist will be something like:
[ { key: 'component',
value: { name1: ..., name2: ... } },
{ key: 'component2',
value: { name1: ..., name2: ... } } ]
The original dict has been remapped into an array of "records," each with key and value pairs. This "array of records" pattern is very common in D3 work, and JavaScript in general. If you need to loop over the sub-structures (e.g. the name1, name2, ... values, d3.entries can be applied at multiple levels of the original structure, as those dict-to-list transforms are required.
Since this answer is called out in the comments as wrong, here's a working example of using an object ("dict") as a data source for a D3 program: first in a simple loop, then secondarily using the idiomatic d3 .data(...).enter() pipeline.
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
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.
I have following json:
{
"responseHeader": {
"status": 0,
"QTime": 1
},
"spellcheck": {
"suggestions": [
"a",
{
"numFound": 4,
"startOffset": 0,
"endOffset": 1,
"suggestion": [
"api",
"and",
"as",
"an"
]
},
"collation",
"api"
]
}
}
I want to access the 'suggestion' array and for that I am using this in jQuery:
$.getJSON('http://localhost:8983/solr/suggest/?q=' + query + '&wt=json&json.wrf=?', {
})
.done(function(response){
// just for testing
alert(response.spellcheck.suggestions.suggestion); // error: response.spellcheck is not defined
});
The value of 'response.spellcheck' is shown undefined whereas 'response.responseHeader' shows [object Object] and also I can access elements under responseHeader. But I cannot figure out what's the issue with 'spellcheck'. Help!
suggestions.suggestions can't work. suggestions is an array. You need to index the array with the [] operator to get to a specific suggestion.
Specifically, based on the JSON you posted, you want suggestions[1].suggestion.
use console.log for printing the response then you can do accordingly
The correct spelling is response.spellcheck.suggestions (you have used suggesstions) and this is an array, so you can look at its context using the index... for example:
alert(response.spellcheck.suggestions.suggestion[0]); // "a"
So you need:
response.spellcheck.suggestions.suggestion[1].suggestion
Example on JS Fiddle.
I am trying to parse the following JSON with jQuery and get each id value. Can anyone advise?
[
{
"id": "1",
"name": "Boat"
},
{
"id": "2",
"name": "Cable"
}
]
So far I have:
$.each(test, function(i,item){
alert(item);
});
But that simply lists every value. How can I
That'll list every object in your array, to get the id property of the one you're on, just add .id like this:
$.each(test, function(i,item){
alert(item.id);
});
If test is a string containing JSON, you can parse it with jQuery.parseJSON, which will return a JavaScript object.
If test is written like this:
var test = [
{
"id": "1",
"name": "Boat"
},
{
"id": "2",
"name": "Cable"
}
];
...it already is a JavaScript object; specifically an array. jQuery.each will loop through each array entry. If you want to loop through the properties of those entries as well, you can use a second loop:
$.each(test, function(outerKey, outerValue) {
// At this level, outerKey is the key (index, mostly) in the
// outer array, so 0 or 1 in your case. outerValue is the
// object assigned to that array entry.
$.each(outerValue, function(innerKey, innerValue) {
// At this level, innerKey is the property name in the object,
// and innerValue is the property's value
});
});
Live example