how to make an array from json array - javascript

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>

Related

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

jquery - required help in convert json to javascript array

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));

loop thought nested json array

I want to access salesId of json array but sales is an array also, so do loop twice?
var json = [
{
'id':1,
'sales':
[
{'salesId':123},
{'salesId':456}
]
},
{
'id':2,
'sales':
[
{'salesId':789},
{'salesId':111213}
]
}
];
for (var i in json) {
for (var j in json[i].sales) {
var result = json[i].sales[j].salesId; // here "result" will get salesId
}
}
See by yourself : here
How do you want the output?
json.map(function(x){ return x.sales.map(function(y){return y.salesId})})
returns ids per object
"[[123,456],[789,111213]]"
You can use inner loop instead, incase salesId is dynamic in sales.
for(var i=0;i<json.length;i++){
salesItem = json[i].sales;
for(var j=0;j<salesItem.length;j++){
var item = salesItem[j];
console.log(item.salesId);
}
}
If you don't care about the id you could simply flatten the array like so:
var newArray = json.reduce(function(p,c,i){
return i>1 ? p.concat(c.sales) : p.sales.concat(c.sales);
});
which will give you:
[ // newArray
{'salesId':123},
{'salesId':456},
{'salesId':789},
{'salesId':111213}
]
You could also use reduce to return just an array of salesId too if you wanted.
You don't need to loop twice
//loop through the json array that holds objects
for (var i=0; i<json.length; i++) {
var obj = json[i]; //reference to each object
var sales = obj.sales;
sales.forEach(function(element, index) {
console.log(element.salesId);
});
}
Here are two other ways. Not suggesting these are better, just 'other' ways.
var json = [
{
'id':1,
'sales':
[
{'salesId':123},
{'salesId':456}
]
},
{
'id':2,
'sales':
[
{'salesId':789},
{'salesId':111213}
]
}
];
one way:
var results = [];
for(i=0;i<json.length;i++){
results.push ( JSON.stringify(json[i].sales).match(/(\d+)/g,function($1){
return $1
}))
};
results; // [["123", "456"], ["789", "111213"]]
another way:
var str;
for(i=0;i<json.length;i++){
str = str + JSON.stringify(json[i].sales);
};
str = str.match(/(\d+)/g,function($1){
return $1
})
str; //["123", "456", "789", "111213"]

How to convert an array of objects into a mapped object in JavaScript?

How can I convert something like initialArray array of JSON objects into finalObject map?
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
];
var finalObject = {
'id1':'name1',
'id2':'name2',
'id3':'name3',
'id4':'name4'
}
Things to consider:
IDs are strings.
I tried for in loop - couldn't make it to work - http://jsfiddle.net/5af9R/23/
Any ideas?
You need to operate on the objects in your array, not strings containing their indexes in the array.
You should also use a regular for loop to iterate over an array.
Your JSFiddle, fixed:
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var i = 0 ; i < x.length ; i++ ){
var obj = x[i];
resp[obj.id] = obj.img;
}
document.write( JSON.stringify(resp, undefined, 2) );
​
DEMO
You can loop over the array, and for each object, add a new property to finalObject whose property name is the id, and whose value is the name.
var finalObject = {};
for (var i = 0, max = initialArray.length; i < max; i++)
finalObject[initialArray[i].id] = initialArray[i].name;
resp[key.id] = key.img;
You correctly call it key. But you need a value;
resp[x[key].id] = x[key].img;
var finalObject = initialArray.reduce(function(ret, obj){
ret[obj.id] = obj.name;
return ret;
}, {});
This solution is specific to the property names for the specific question, but Array.prototype.reduce is a function I use all the time for any sort of array iteration that requires a non-array result.
You're not using For In correctly jsFiddle
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var key in x ){
resp['id' + x[key].id] = x[key].img;
}
document.write( JSON.stringify(resp, undefined, 2) );
​
for (var i=0; i<x.length; i++) {
var id = 'id' + x[i].id;
var img = x[i].img;
resp[id] = img;
}
if i have understood correctly you can do something like
var x =' [ {"id":"1", "img":"img1"}, {"id":"2", "img":"img2"}, {"id":"3", "img":"img3"}]';
var resp = {};
var json = $.parseJSON(x);
$(json).each(function(i,v){
resp[v.id]=v.img;
});
console.log( resp);
DEMO
you talked about json but in the fiddle you provided there was no json even jquery was not added as a resource so i made some assumptions
Today I was on the same question and I didn't find an answer here, except the answer of #adam-rackis.
The way I found is :
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
],
finalObject = {};
$.each(initialArray, function(k,v) {
finalObject[v.name] = v.value;
});

Javascript accessing name/value pairs

I'm getting JSON name/value pairs that looks like this:
{
"Name":"parentid",
"Value":"blah"
},
{
"Name":"siteid",
"Value":"blah"
},
{
"Name":"sitename",
"Value":"blah"
}
But I would like to access the "name" value as the KEY, and the "value" value as the VALUE. Is there an elegant way to turn that piece of JSON into something like this?
{'parentid', 'blah'},
{'sitename', 'blah'}
Try this:
var items = [
{
"Name":"parentid",
"Value":"blah"
},
{
"Name":"siteid",
"Value":"blah"
},
{
"Name":"sitename",
"Value":"blah"
}
];
var results = new Object();
for (var i = 0; i < items.length; i++)
{
results[items[i].Name] = items[i].Value;
}
This will result in something like:
var results = { parentid: "Blah", siteid: "Blah", sitename: "Blah" };
One way to do it.
var json = [
{
"Name":"parentid",
"Value":"blah"
},
{
"Name":"siteid",
"Value":"blah"
},
{
"Name":"sitename",
"Value":"blah"
}
];
for ( var i = 0, l = json.length, obj; i < l; i++ )
{
obj = json[i];
json[i] = new Object();
json[i][obj.Name] = obj.Value;
}
// console.log() requires Firebug
console.log( json );
function objectflatten (array) {
var out = {}, i;
for(i = 0; i < array.length; i++) {
out[array[i].name] = array[i].value;
}
return out;
}
This is a function that will take an object in the form you presented, and output it as a "normal" object with the name values as keys, and the value values as values.
I'd recommend using the for( ... in ... ) method for this task. It'll grab the key names like you need.
var jsonObj = eval( '([{ "Name":"parentid", "Value":"blah" }])' );
for( var i = 0, assoc = {}, key; i < jsonObj.length; ++i )
{
for( key in jsonObj[ i ] ) // <-- this right here
{
assoc[ key ] = jsonObj[ i ][ key ];
}
}
and you end up with (from Firebug)
Object Name=parentid Value=blah
that can be accessed by object.key or object[ 'key' ] (in our case assoc.Name or assoc[ 'Value' ])
here's a link from Douglas Crockford from Yahoo! about using it as well - http://yuiblog.com/blog/2006/09/26/for-in-intrigue/
I'm assuming you are using PHP, and the PHP echoes you assosiatice aray like this:
echo json_encode($result);
In your javascript, you could do this:
// Soemthing retrieves php result and puts it in `var result`.
data = eval("(" + result+ ")");
alert(data.parentid);
I'm not sure if this is what you want, but it's a solution.

Categories