jquery - required help in convert json to javascript array - javascript

I have json data like this.
[{"data":"85"},{"data":"83"},{"data":"75"},{"data":"87"},{"data":"86"},{"data":"0"},{"data":"84"}].
I wanted to remove the "data": and curly brackets.
I wanted the output to be like this.
[85,83,75,87,86,0,84]
Someone please help me on converting it to like that.

You tagged your question with jQuery, so heres an answer using it:
var input = [{ "data": "85" }, { "data": "83" }, { "data": "75" }, { "data": "87" }, { "data": "86" }, { "data": "0" }, { "data": "84" }];
var output = $.map(input, function (e) { return e.data; });

var newArray = [];
jsonData.forEach(function(i) {
newArray.push(i.data);
});
Where jsonData is the name of the variable storing your JSON data.

Loop through the array and extract data value like this
var obj= [{"data":"85"},{"data":"83"},{"data":"75"},{"data":"87"},{"data":"86"},{"data":"0"},{"data":"84"}];
var arr = [];
for ( var i = 0; i < obj.length;i++){
arr.push(obj[i].data);
}

Please check the following code.
var myMessage = [{"data":"85"},{"data":"83"},{"data":"75"},{"data":"87"},{"data":"86"},{"data":"0"},{"data":"84"}];
var obj2 = eval(myMessage);
var myArray = new Array();
for(var i in obj2){
myArray[i] = obj2[i].data;
}
console.log(myArray);
Cheers Subh

var msg = '[{"data":"85"},{"data":"83"},{"data":"75"},{"data":"87"},{"data":"86"},{"data":"0"},{"data":"84"}]';
var msgObject = JSON.parse(msg);
var output = new Array();
for (var i = 0; i < msgObject.length; i++) {
output.push(msgObject[i].data);
}
alert(JSON.stringify(outputObject));

Related

how to make an array from json array

I have a json response like this,
"meteo_inverter_analysis":{
"Id93922.1":{
"inverter_id":"Id93922.1", "total_electricity_generated":1567.7910000000002
},
"Id93922.2":{
"inverter_id":"Id93922.2", "total_electricity_generated":1468.4869999999999
},
"Id93922.3":{
"inverter_id":"Id93922.3","total_electricity_generated":498.7319999999999
},
"Id93922.4":{
"inverter_id":"Id93922.4","total_electricity_generated":461.8369999999999
}
}
from that response i want to create an js array from total_electricity_generated. The array would be:
var array = [1567.7910000000002, 1468.4869999999999, 498.7319999999999, 461.8369999999999]
Can anyone help me how to do it? TIA
You can get the keys of the meteo_inverter_analysis and then loop over to that keys to get the property value of Id93922.*
var data = {"meteo_inverter_analysis":{
"Id93922.1":{
"inverter_id":"Id93922.1",
"total_electricity_generated":1567.7910000000002
},
"Id93922.2":{
"inverter_id":"Id93922.2",
"total_electricity_generated":1468.4869999999999
},
"Id93922.3":{
"inverter_id":"Id93922.3",
"total_electricity_generated":498.7319999999999
},
"Id93922.4":{
"inverter_id":"Id93922.4",
"total_electricity_generated":461.8369999999999
}
}
};
var keys = Object.keys(data.meteo_inverter_analysis);
var arr = keys.map(key => data.meteo_inverter_analysis[key].total_electricity_generated
);
console.log(arr);
I think the following example will help you:
<script>
var car =new Array();
var myObj, i;
myObj = {
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
};
for (i = 0; i < myObj.cars.length; i++) {
car[i]= myObj.cars[i] + "<br>";
}
</script>

concat JSON objects in a loop (No JQuery)

Update: Fixed mistakes in example code. Turned out my problem was caused by an additional 'records' in var jsonVar = jsonVar.concat(results.records);
How can I concat JSON objects in a loop? I can concat 2 JSON objects like this:
var json1 = {
"records": [{
"id": 28100988,
"work_text_reviews_count": 13,
"average_rating": "3.10"
}, {
"id": 10280687,
"work_text_reviews_count": 80,
"average_rating": "3.87"
}]
}
var json2 = {
"records": [{
"id": 16135639,
"work_text_reviews_count": 0,
"average_rating": "0.00"
}, {
"id": 17978337,
"work_text_reviews_count": 2414,
"average_rating": "3.76"
}, {
"id": 360721218,
"work_text_reviews_count": 4924,
"average_rating": "3.98"
}]
}
var json3 = json1.records.concat(json2.records);
To add a 3rd JSON object I know I can just add .concat(json3.records)
but how can I dynamically concatenate JSON objects in a loop?
Example:
Say values.length = 5, this means 5 JSON objects need to be concatenated.
for (var i=0; i<values.length ; i++) {
response= UrlFetchApp.fetch(url);
Utilities.sleep(1000);
var results = JSON.parse(response);
// this works now (had a typo here)
var jsonVar = jsonVar.concat(results.records);
}
You could do something like:
var jsonVar = [];
for (var i=0; i<values.length ; i++) {
results= UrlFetchApp.fetch(url);
Utilities.sleep(1000);
var results = JSON.parse(response);
jsonVar = jsonVar.concat(results.records);
}
But I am not sure if this would work because UrlFetchApp.fetch() seems to be asynchronous. This means the response is not guaranteed to be initialized to correct value if it takes more than 1000ms
A JSON object is a Javascript object. You can dynamically set the object name
for (var i=0; i<values.length ; i++) {
json[i].records.concat(json[i + 1].records)
}

How to convert array of key–value objects to array of objects with a single property?

I have an array of objects like this:
[
{ "key": "fruit", "value": "apple" },
{ "key": "color", "value": "red" },
{ "key": "location", "value": "garden" }
]
I need to convert it to the following format:
[
{ "fruit": "apple" },
{ "color": "red" },
{ "location": "garden" }
]
How can this be done using JavaScript?
You can use .map
var data = [
{"key":"fruit","value":"apple"},
{"key":"color","value":"red"},
{"key":"location","value":"garden"}
];
var result = data.map(function (e) {
var element = {};
element[e.key] = e.value;
return element;
});
console.log(result);
also if you use ES2015 you can do it like this
var result = data.map((e) => {
return {[e.key]: e.value};
});
Example
Using an arrow function, with the data called arr
arr.map(e => {
var o = {};
o[e.key] = e.value;
return o;
});
This generates a new Array and does not modify the original
It can be simplified down to one line as
arr.map(e => ({[e.key]: e.value}));
If you can't assume arrow function support yet, you would write this longhand
arr.map(function (e) {
var o = {};
o[e.key] = e.value;
return o;
});
Using map (as suggested in other answers) or the following will do what you want...
var data = [{"key":"fruit","value":"apple"},{"key":"color","value":"red"},{"key":"location","value":"garden"}];
var obj = {};
for(var i = 0; i < data.length; i++) {
obj[data[i]["key"]] = data[i]["value"];
}
In Javascript, obj.property and obj['property'] return same things.
obj['property'] is more flexible because the key 'property' could be a string with some space :
obj['pro per ty'] // work
obj.pro per ty // not work
or
var a = 'property';
obj.a == obj.property // => false
obj[a] == obj.property // => true
So you could try that.
var data = [{"key":"fruit","value":"apple"},{"key":"color","value":"red"},{"key":"location","value":"garden"}]
var new_data = [];
var data_length = data.length; // just a little optimisation for-loop
for (var i = 0; i < data_length; i++) {
var item = data[i]; // to have a vision close of foreach-loop (foreach item of collection)
new_data[i] = {};
new_data[i][item.key] = item.value;
}
console.log(new_data);
// [{"fruit":"apple"},{"color":"red"},{"location":"garden"}]
What you currently have is an array of object, each having two attributes, key and value. If you are not aware of map, you can always run a forEach loop on this array and rearrange the data. Try something like below:
function() {
var newArray = [];
oldArray.forEach(function(x){
var obj= {};
obj[x.key] = x.value;
newArray.push(obj);
});
console.log(newArray);
}
here oldArray is your original data

JSON to Multidimensional Javascript Object

I'm loading an external JSON file into javascript, the JSON file looks like this:
[
{
"name":"Apple",
"year":8,
"records_lost":12367232
},
{
"name":"178.com",
"year":7,
"records_lost":10000000
},
{
"name":"Accendo Insurance Co. ",
"year":7,
"records_lost":175350
}
]
Eventually, I want to access the data via a Javascript object like this (don't mind the syntax). The point is that name will be a parent with its own meta-data.
"Apple":
"year":8,
"records_lost":12367232
"178.com":
"year":7,
"records_lost":10000000
This is the code I've already written for this part, which doesn't make name parent yet and only saves the last row of the JSON file into the array (+= instead of = would fix this, but delivers ugly values, obviously).
function initJSON() {
loadJSON(function(response) {
var JSONParse = JSON.parse(response);
var i;
for (i in JSONParse) {
JSONdata.name.i = JSONParse[i].name;
JSONdata.year = JSONParse[i].year;
JSONdata.recl = JSONParse[i].records_lost;
}
});
}
initJSON();
Thanks in forward.
Try utilizing Array.prototype.map() , delete operator
var data = [{
"name": "Apple",
"year": 8,
"records_lost": 12367232
}, {
"name": "178.com",
"year": 7,
"records_lost": 10000000
}, {
"name": "Accendo Insurance Co. ",
"year": 7,
"records_lost": 175350
}];
var res = data.map(function(val, key) {
var obj = {};
obj[val.name] = val;
delete obj[val.name].name;
return obj
});
document.getElementsByTagName("pre")[0].textContent = JSON.stringify(res, null, 4);
<pre></pre>
it should be :
var i;
for (i in JSONParse) {
JSONdata.name = i.name;
JSONdata.year = i.year;
JSONdata.recl = i.records_lost;
}
unless your loop was different:
var i;
for (i = 0; i < JSONParse.length; i++) {
JSONdata.name = JSONParse[i].name;
JSONdata.year = JSONParse[i].year;
JSONdata.recl = JSONParse[i].records_lost;
}

How to push elements in JSON from javascript array

I want to add javascript array values into JSON values object. The other element is also replaced my element like recipients, subject, message. I got Json like:
Below is my code.
var BODY = {
"recipients": {
"values": [
]
},
"subject": title,
"body": message
}
var values = [];
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": {
"_path": "/people/"+names[ln],
},
};
values.push(item1);
}
BODY = JSON.stringify({values: values});
alert(BODY);
I think you want to make objects from array and combine it with an old object (BODY.recipients.values), if it's then you may do it using $.extent (because you are using jQuery/tagged) method after prepare the object from array
var BODY = {
"recipients": {
"values": []
},
"subject": 'TitleOfSubject',
"body": 'This is the message body.'
}
var values = [],
names = ['sheikh', 'muhammed', 'Answer', 'Uddin', 'Heera']; // for testing
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": { "_path": "/people/"+names[ln] }
};
values.push(item1);
}
// Now merge with BODY
$.extend(BODY.recipients.values, values);
DEMO.
If you want to stick with the way you're populating the values array,
you can then assign this array like so:
BODY.values = values;
after the loop.
It should look like this:
var BODY = {
"recipients": {
"values": [
]
},
"subject": title,
"body": message
}
var values = [];
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": {
"_path": "/people/"+names[ln],
},
};
values.push(item1);
}
BODY.values = values;
alert(BODY);
JSON.stringify() will be useful once you pass it as parameter for an AJAX call.
Remember: the values array in your BODY object is different from the var values = [].
You must assign that outer values[] to BODY.values. This is one of the good things about OOP.
You can directly access BODY.values:
for (var ln = 0; ln < names.length; ln++) {
var item1 = {
"person": {
"_path": "/people/"+names[ln],
},
};
BODY.values.push(item1);
}
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

Categories