Here is the JSON example:
jsonData:
{ "Device": { "Content": { "UL": { "index0": "12", "index1": "1", .... "index31": "5", } } } }
This is what I tried, but it didn't work:
var index = [];
var jsonDoc = JSON.parse(data);
for(var i =0; i<32 ; i++)
{
var $arr = "index"+i;
index.push( jsonDoc.Device.Content.UL.$arr);
}
How can I extract the index from 1 to 31 and put it in the index array?
You can access hashes with the [] operator as well:
index.push( jsonDoc.Device.Content.UL[$arr]);
try converting JSON to array .
var o = jsonDoc.Device.Content.UL;
var arr = Object.keys(o).map(function(k) { return o[k] });
refer: Converting JSON Object into Javascript array
You can use for statement to iterate through an object's values:
var index = [];
for(var name in jsonDoc.Device.Content.UL)
{
index.push(jsonDoc.Device.Content.UL[name]));
}
Related
I'm looking to count the occurances of certain strings within JSON - in this instance sensorUUID.
var newDataArray = JSON.stringify(conData);
JSON
[{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362037.111941,"uID":"22489710_3_10"},{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362036.109874,"uID":"22489710_3_10"}]
I've tried the following code but it is returning an empty object.
var obj = {};
for (var i = 0, j = newDataArray.length; i < j; i++) {
if (obj[newDataArray[i].sensorUUID]) {
obj[newDataArray[i]]++;
}
}
console.log(obj);
The full JSON file will have multiple sensor ID's within it, I am looking to return the number of unique sensor ID.
e.g.
22489710 has 10 occurrences
63846683 has 23 occurrences
etc.
the if condition in for loop is correct but you have to initialize count as 1 for the first time you find a particular sensorUUID.
var newDataArray = [{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362037.111941,"uID":"22489710_3_10"},{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362036.109874,"uID":"22489710_3_10"}];
var obj = {};
for (var i = 0, j = newDataArray.length; i < j; i++) {
if (obj[newDataArray[i].sensorUUID]) {
obj[newDataArray[i].sensorUUID]++;
}else{
obj[newDataArray[i].sensorUUID] = 1;
}
}
// obj gives you count for each unique sensorUUID.
console.log(obj);
//if you want total count of all sensorUUID you can sum all the values in obj.
var count = Object.values(obj).reduce((a, b) => a + b, 0);
console.log(count);
you can set a variable count and iterate over the array using Array#forEach and check whether the object has the property sensorUUID using Object#hasOwnProperty if yes, increment the count
var data = [{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362037.111941,"uID":"22489710_3_10"},{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362036.109874,"uID":"22489710_3_10"}];
var count = 0;
data.forEach((x)=>{
if(x.hasOwnProperty('sensorUUID'))
count++;
});
console.log(count);
You can simply iterate through the json array using array.reduce and count the occurances of sensorUUID and store it inside the new object.
var json = [{
"blobJson": "x",
"deviceMfg": 10,
"eventCode": 0,
"sensorClass": 3,
"sensorUUID": "22489710",
"timeStamp": 1500362037.111941,
"uID": "22489710_3_10"
}, {
"blobJson": "x",
"deviceMfg": 10,
"eventCode": 0,
"sensorClass": 3,
"sensorUUID": "22489710",
"timeStamp": 1500362037.111941,
"uID": "22489710_3_10"
}, {
"blobJson": "x",
"deviceMfg": 10,
"eventCode": 0,
"sensorClass": 3,
"sensorUUID": "22489710123",
"timeStamp": 1500362036.109874,
"uID": "22489710_3_10"
}];
let count = json.reduce((newObj, obj) => {
if(newObj[obj.sensorUUID]) {
newObj[obj.sensorUUID] = newObj[obj.sensorUUID]+1;
} else {
newObj[obj.sensorUUID] = 1;
}
return newObj;
}, {});
console.log(count);
https://jsfiddle.net/7jjoches/1/
Using jquery method $.parseJSON you have to convert the JSON string to a JSON object and only then you can work with it.
var conData = '[{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362037.111941,"uID":"22489710_3_10"},{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362036.109874,"uID":"22489710_3_10"}]';
var newDataArray = $.parseJSON(conData);
console.dir(newDataArray);
var obj = {};
for (var i = 0; i< newDataArray.length; i++) {
obj[newDataArray[i].sensorUUID] = obj[newDataArray[i].sensorUUID] ? obj[newDataArray[i].sensorUUID]+1 : 1;
}
console.log(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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
I am trying to use javascript array in mongodb $in
It's always wrapping it with single quotes // '"Indoor","Outdoor","Both"'
I need it to work or like this -> "Indoor","Outdoor","Both"
url_parts.query.Venue ='Indoor,Outdoor,Both'
var query={};
if(url_parts.query.Venue!= undefined){
var myarr = url_parts.query.Venue.split(",");
var string='';
for (var i = 0; i < myarr.length; i++) {
string+="\""+myarr[i]+"\",";
};
string = string.substring(0, string.length - 1)
query.venues = { $in:[string]};
}
attraction.find(query).lean().exec(function(err, attrs) {....
As I said $in takes an array:
var url_parts.query.Venue ='Indoor,Outdoor,Both';
var query = {};
query.venues = url_parts.query.Venue.split(",");
So now query looks like this:
{ "venues" : { "$in" : [ "Indoor", "Outdoor", "Both" ] } }
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"]
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.