This is my static values which is having id with names:
var staticValues = [
{ "id": "1", "name": "PEKKA" },
{ "id": "2", "name": "Golem" },
{ "id": "3", "name": "Vigilane" },
{ "id": "4", "name": "SpiderMan" },
{ "id": "5", "name": "Archer" },
{ "id": "6", "name": "SuperMan" }
]
This is is my returned value from my method:
var myReturnedValues = [
[ [ "2", "4" ] ],
[ [ "5", "5" ] ],
[ [ "1", "3" ] ],
[ [ "4", "3" ] ]
]
My output needs to be like this:
var myReturnedValues = [
[ [ "Golem", "SpiderMan" ] ],
[ [ "Archer", "Archer" ] ],
[ [ "PEKKA", "Vigilante" ] ],
[ [ "SpiderMan", "Vigilante" ] ]
]
What am trying to do here is I have to compare staticValues and myReturnedValues and return names with respect to their ids instead of returning only ids alone. I tried some more ways with underscore.js but failed. Can someone give me idea about that?
This is how my method looks like:
var staticValues = [ /* here I have the whole static data */ ];
$scope.getCategories = function() {
var myReturnedValues = mainSteps.map(x => [x.steps.map(y => y.category)]);
return myReturnedValues;
}
Code After edited ,
$scope.getCategories =function(){
var myReturnedValues =mainSteps.map(x => [x.steps.map(y => y.category+"\n"+"\n"+"\n")]);
//return myReturnedValues;
console.log('meeee before',angular.toJson(myReturnedValues));
newval = {};
$.each(staticValues ,function(i,v) {
console.log('meeee staticCategories',angular.toJson(staticValues ));
newval[v.id] = v.name;
});
$.each(myReturnedValues,function(i,v){
$.each(v[0],function(x,t){
myReturnedValues[i][0][x] = newval[t];
});
});
console.log('meeee after',angular.toJson(myReturnedValues));
return myReturnedValues;
}
Start by converting staticValues to a key => value object:
names = {}
staticValues.forEach(obj => names[obj.id] = obj.name);
Then iterate myReturedValues and replace ids with names as you go:
var staticValues = [
{ "id": "1", "name": "PEKKA" },
{ "id": "2", "name": "Golem" },
{ "id": "3", "name": "Vigilane" },
{ "id": "4", "name": "SpiderMan" },
{ "id": "5", "name": "Archer" },
{ "id": "6", "name": "SuperMan" }
]
var myReturnedValues = [
[ [ "2", "4" ] ],
[ [ "5", "5" ] ],
[ [ "1", "3" ] ],
[ [ "4", "3" ] ]
]
names = {}
staticValues.forEach(x => names[x.id] = x.name)
res = myReturnedValues.map(sub =>
[sub[0].map(id => names[id])]
)
console.log(res)
Try the following loops:
newval = {};
$.each(staticValues,function(i,v) {
newval[v.id] = v.name;
});
var myReturedValues = [
[ [ "2", "4" ] ],
[ [ "5", "5" ] ],
[ [ "1", "3" ] ],
[ [ "4", "3" ] ]
];
$.each(myReturedValues,function(i,v){
$.each(v[0],function(x,t){
myReturedValues[i][0][x] = newval[t];
});
});
demo: https://jsfiddle.net/cgk478g8/
With underscore you can try like this:
var staticValues = [
{ "id": "1", "name": "PEKKA" },
{ "id": "2", "name": "Golem" },
{ "id": "3", "name": "Vigilane" },
{ "id": "4", "name": "SpiderMan" },
{ "id": "5", "name": "Archer" },
{ "id": "6", "name": "SuperMan" }
];
var myReturedValues = [
[ [ "2", "4" ] ],
[ [ "5", "5" ] ],
[ [ "1", "3" ] ],
[ [ "4", "3" ] ]
];
var data = _.chain(myReturedValues).map(function(d) {
//map the myReturedValues
return d[0].map(function(id) {
//use underscore to search in the staticValues and return name
return _.find(staticValues, function(svalue) {
return svalue.id == id
}).name
});
}).value();
console.log(data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
Related
I need to find value of type2.id where id is 7 in the following object
[
{
"type1": {
"id": "1",
"value": "val1"
},
"type2": [
{
"id": "2",
"value": "val2"
}
]
},
{
"type1": null,
"type2": [
{
"id": "5",
"value": "val5"
}
]
},
{
"type1": {
"id": "3",
"value": "val3"
},
"type2": [
]
},
{
"type1": {
"id": "4",
"value": "val4"
},
"type2": [
{
"id": "7",
"value": "val7"
}
]
}
]
Please notice type1 is a simple object and type 2 is an array here, there can be empty array in type2 as well.
arr.find(({type2}) => type2[0]?.id === '7')?.type2[0].value
let value = null;
// First way using forEach
obj.forEach(item => {
if (item.type2 && item.type2.length > 0) {
item.type2.forEach(type2 => {
if (type2.id === '7') {
value = type2.value;
}
});
}
});
console.log("first way : ", value);
// Second way using map and filter
let type2Array = obj.map(obj => obj.type2).flat()
value = type2Array.filter(obj => obj.id === '7').at(0)?.value
console.log("second way : ", value);
<script>
const obj = [{
"type1": {
"id": "1",
"value": "val1"
},
"type2": [{
"id": "2",
"value": "val2"
}]
},
{
"type1": null,
"type2": [{
"id": "5",
"value": "val5"
}]
},
{
"type1": {
"id": "3",
"value": "val3"
},
"type2": [
]
},
{
"type1": {
"id": "4",
"value": "val4"
},
"type2": [{
"id": "7",
"value": "val7"
}]
}
];
</script>
Try this
const data = [
{
type1: {
id: "1",
value: "val1",
},
type2: [
{
id: "2",
value: "val2",
},
],
},
{
type1: null,
type2: [
{
id: "5",
value: "val5",
},
],
},
{
type1: {
id: "3",
value: "val3",
},
type2: [],
},
{
type1: {
id: "4",
value: "val4",
},
type2: [
{
id: "7",
value: "val7",
},
],
},
];
const result = data.find((object) => {
const { type2 } = object;
if (!type2) {
return false;
}
const [ firstFromType2 ] = type2;
if (!firstFromType2) {
return false;
}
return firstFromType2.id === '7';
});
console.log(result);
const data = [{"type1":{"id":"1","value":"val1"},"type2":[{"id":"2","value":"val2"}]},{"type1":null,"type2":[{"id":"5","value":"val5"}]},{"type1":{"id":"3","value":"val3"},"type2":[]},{"type1":{"id":"4","value":"val4"},"type2":[{"id":"7","value":"val7"}]}]
console.log(data.flatMap(i=>i.type2).find(({id})=>id==='7')?.value)
Assign the array to a const and make a nested map.
const foundObj = array.map(obj => obj.type2.map(type2obj => type2obj.id === '7')));
const value = foundObj.value
fiddle here: https://jsfiddle.net/
I have the following array
[ {
"contactId": "a87d096gd5fuop",
"firstName": "John Doe",
"registrationTypes": {
"selectedOptions": [
{
}
],
"subTotal": 1620.003
},
"foo1": {
"selectedOptions": [
],
"subTotal": 0
},
"events": {
"selectedOptions": [
{
"id": "1",
"name": "T1",
"value": "4550006:3",
},
{
"id": "2",
"name": "T2",
"value": "4550005:3",
},
{
"id": "3",
"name": "T3",
"value": "4550003:3",
}
],
"subTotal": 135.003
},
"freeNetworkingFunctions": {
},
"total": 1755.0059999999999
},
{
"contactId": "a097f",
"firstName": "David",
"registrationTypes": {
"selectedOptions": [
{}
],
"subTotal": 899.998
},
"foo1": {
"selectedOptions": [
],
"subTotal": 0
},
"member": {
"selectedOptions": [
{
}
],
"subTotal": 228.8
},
"events": {
"selectedOptions": [
{
"id": "4",
"name": "T4",
"value": "4550002:2",
},
{
"id": "5",
"name": "T5",
"value": "4550001:2",
},
{
"id": "6",
"name": "T6",
"value": "4550003:2",
}
],
"subTotal": 135.003
},
"total": 1263.801
}
]
From the above array, I want to extract events, loop all the data and get only values. So my new array should be something like this:
[ {
"contactId": "a87d096gd5fuop",
"firstName": "John Doe",
"registrationTypes": {
"selectedOptions": [
{
}
],
"subTotal": 1620.003
},
"foo1": {
"selectedOptions": [
],
"subTotal": 0
},
"events": [
"4550006:3"
"4550005:3",
"4550003:3",
],
},
"freeNetworkingFunctions": {
},
"total": 1755.0059999999999
},
{
"contactId": "a097f",
"firstName": "David",
"registrationTypes": {
"selectedOptions": [
{}
],
"subTotal": 899.998
},
"foo1": {
"selectedOptions": [
],
"subTotal": 0
},
"member": {
"selectedOptions": [
{
}
],
"subTotal": 228.8
},
"events": [
"4550004:2"
"4550008:3",
"4550003:3",
],
"subTotal": 135.003
},
"total": 1263.801
}
]
So it should return the original array, however, events value data should be in one array.
var arr = [];
var r(var i=0;i<data.length;i++){
data.push(arr[i].value);
}
var newData = [...data, arr]
However, this doesn't work. Any help would be highly appreciated.
Use map twice - once on the dataset to iterate over the objects, and within that map to get an array of values from the selectedOptions.
const data=[{contactId:"a87d096gd5fuop",firstName:"John Doe",registrationTypes:{selectedOptions:[{}],subTotal:1620.003},foo1:{selectedOptions:[],subTotal:0},events:{selectedOptions:[{id:"1",name:"T1",value:"4550006:3"},{id:"2",name:"T2",value:"4550005:3"},{id:"3",name:"T3",value:"4550003:3"}],subTotal:135.003},freeNetworkingFunctions:{},total:1755.0059999999999},{contactId:"a097f",firstName:"David",registrationTypes:{selectedOptions:[{}],subTotal:899.998},foo1:{selectedOptions:[],subTotal:0},member:{selectedOptions:[{}],subTotal:228.8},events:{selectedOptions:[{id:"4",name:"T4",value:"4550002:2"},{id:"5",name:"T5",value:"4550001:2"},{id:"6",name:"T6",value:"4550003:2"}],subTotal:135.003},total:1263.801}];
const out = data.map(obj => {
// Destructure the selected options from the
// rest of each object
const { events: { selectedOptions }, ...rest } = obj;
// `map` over the options to just get an array of values
const events = selectedOptions.map(option => {
return option.value;
});
// Return a new object with the new events property
// combined with the other properties again
return { ...rest, events };
});
console.log(out);
Additional documentation
Destructuring assignment
Rest parameters
Spread syntax
I'm using Google analytics API to get a JSON message from the server. The message I receive is this one :
{
"reports": [
{
"columnHeader": {
"dimensions": [
"ga:landingPagePath"
],
"metricHeader": {
"metricHeaderEntries": [
{
"name": "ga:pageviews",
"type": "INTEGER"
},
{
"name": "ga:sessions",
"type": "INTEGER"
}
]
}
},
"data": {
"rows": [
{
"dimensions": [
"/-chandigarh/axis-bank-sarsini-branch_chandigarh_chg_850458.html"
],
"metrics": [
{
"values": [
"1",
"1"
]
}
]
},
{
"dimensions": [
"/267249-1.compliance-alex.xyz"
],
"metrics": [
{
"values": [
"29",
"10"
]
}
]
},
{
"dimensions": [
"/267249-1.compliance-don.xyz"
],
"metrics": [
{
"values": [
"27",
"9"
]
}
]
},
{
"dimensions": [
"/267249-1.compliance-fred.xyz"
],
"metrics": [
{
"values": [
"20",
"7"
]
}
]
},
{
"dimensions": [
"/abohar/axis-bank-the-fazilka-central-cooperative-bank-ltd-branch_abohar_frp_135.html"
],
"metrics": [
{
"values": [
"1",
"1"
]
}
]
},
{
"dimensions": [
"/about-us/career.htm"
],
"metrics": [
{
"values": [
"8",
"5"
]
}
]
},
{
"dimensions": [
"/about-us/company-profile.htm"
],
"metrics": [
{
"values": [
"34",
"14"
]
}
]
},
{
"dimensions": [
"/about-us/infrastructure.htm"
],
"metrics": [
{
"values": [
"3",
"1"
]
}
]
},
{
"dimensions": [
"/adilabad/gk-hospital-multispeciality-care_adilabad_adi_399806.html"
],
"metrics": [
{
"values": [
"2",
"1"
]
}
]
},
{
"dimensions": [
"/ahmedabad/akhani-jagdish-kumar_ahmedabad_ahd_1124498.html"
],
"metrics": [
{
"values": [
"7",
"3"
]
}
]
}
],
"totals": [
{
"values": [
"3420452",
"1333496"
]
}
],
"rowCount": 347614,
"minimums": [
{
"values": [
"0",
"1"
]
}
],
"maximums": [
{
"values": [
"56660",
"49274"
]
}
],
"isDataGolden": true
},
"nextPageToken": "1000"
}
]
}
I want to parse it and saved data in variable. How will I parse it. I tried many options but didn't get any data from JSON. Result is showing like undefined. I want to fetch the array data of dimensions and values like:
var a = "/-chandigarh/axis-bank-sarsini-branch_chandigarh_chg_850458.html";
var b = 1;
var c = 1;
Supposing your JSON input is stored in the json variable, you could just do:
var json = '{"reports":[{"columnHeader":{"dimensions":["ga:landingPagePath"],"metricHeader":{"metricHeaderEntries":[{"name":"ga:pageviews","type":"INTEGER"},{"name":"ga:sessions","type":"INTEGER"}]}},"data":{"rows":[{"dimensions":["/-chandigarh/axis-bank-sarsini-branch_chandigarh_chg_850458.html"],"metrics":[{"values":["1","1"]}]},{"dimensions":["/267249-1.compliance-alex.xyz"],"metrics":[{"values":["29","10"]}]},{"dimensions":["/267249-1.compliance-don.xyz"],"metrics":[{"values":["27","9"]}]},{"dimensions":["/267249-1.compliance-fred.xyz"],"metrics":[{"values":["20","7"]}]},{"dimensions":["/abohar/axis-bank-the-fazilka-central-cooperative-bank-ltd-branch_abohar_frp_135.html"],"metrics":[{"values":["1","1"]}]},{"dimensions":["/about-us/career.htm"],"metrics":[{"values":["8","5"]}]},{"dimensions":["/about-us/company-profile.htm"],"metrics":[{"values":["34","14"]}]},{"dimensions":["/about-us/infrastructure.htm"],"metrics":[{"values":["3","1"]}]},{"dimensions":["/adilabad/gk-hospital-multispeciality-care_adilabad_adi_399806.html"],"metrics":[{"values":["2","1"]}]},{"dimensions":["/ahmedabad/akhani-jagdish-kumar_ahmedabad_ahd_1124498.html"],"metrics":[{"values":["7","3"]}]}],"totals":[{"values":["3420452","1333496"]}],"rowCount":347614,"minimums":[{"values":["0","1"]}],"maximums":[{"values":["56660","49274"]}],"isDataGolden":true},"nextPageToken":"1000"}]}'
// Parse the JSON into the data variable
var data = JSON.parse(json);
data.reports.forEach(report => {
report.data.rows.forEach(row => {
// row.dimensions will contain your 'dimensions' array
console.log(row.dimensions);
row.metrics.forEach(metric => {
// metric.values will contain your 'values' array
console.log(metric.values);
});
});
});
You will just have to store these properties into your own variables.
Use json.parse
var json = '{"param1":1,"param2":2}',
obj = JSON.parse(json);
alert(obj.param1);
Most browsers e.g. Google support JSON.parse, moreover for those which don't support you can use json2 -> https://github.com/douglascrockford/JSON-js/blob/master/json2.js
I am getting a result in my JavaScript file which I want to convert into another object.
My original result
[
{
"SName": "Set1",
"Elements": [
{
"Id": "3",
"Name": "Name1"
},
{
"Id": "5",
"Name": "Name2"
}
]
},
{
"SName": "Set2",
"Elements": [
{
"Id": "7",
"Name": "Name3"
},
{
"Id": "8",
"Name": "Name4"
}
]
}
]
Convert this to look like array of objects using jQuery or JavaScript. How can I achieve this?
[
{
"SName": "Set1",
"Id": 3,
"Name": "Name1"
},
{
"SName": "Set1",
"Id": 5,
"Name": "Name2"
},
{
"SName": "Set2",
"Id": 7,
"Name": "Name3"
},
{
"SName": "Set2",
"Id": 8,
"Name": "Name4"
}
]
var data = [
{
"SName": "Set1",
"Elements": [
{
"Id": "3",
"Name": "Name1"
},
{
"Id": "5",
"Name": "Name2"
}
]
},
{
"SName": "Set2",
"Elements": [
{
"Id": "7",
"Name": "Name3"
},
{
"Id": "8",
"Name": "Name4"
}
]
}
];
console.log(data);
var newData = data.reduce(function (newArray, currentSet) {
return newArray.concat(currentSet.Elements.map(function (element) {
return Object.assign( { SName: currentSet.SName }, element);
}));
}, []);
console.log(newData);
The key here is the reduce function. What we are doing is creating a brand new array, by looping through each value of the outer array. We continuously concatenate onto our new array with the values we map from the inner array.
You could iterate the array, the Elements and the properties and build a new object and push it to the result set.
var array = [{ "SName": "Set1", "Elements": [{ "Id": "3", "Name": "Name1" }, { "Id": "5", "Name": "Name2" }] }, { "SName": "Set2", "Elements": [{ "Id": "7", "Name": "Name3" }, { "Id": "8", "Name": "Name4" }] }],
result = [];
array.forEach(function (a) {
a.Elements.forEach(function (b) {
var o = { SName: a.SName };
Object.keys(b).forEach(function (k) {
o[k] = b[k];
});
result.push(o);
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6
var array = [{ "SName": "Set1", "Elements": [{ "Id": "3", "Name": "Name1" }, { "Id": "5", "Name": "Name2" }] }, { "SName": "Set2", "Elements": [{ "Id": "7", "Name": "Name3" }, { "Id": "8", "Name": "Name4" }] }],
result = [];
array.forEach(a => a.Elements.forEach(b => result.push(Object.assign({ SName: a.SName }, b))));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this with reduce(), forEach() and Object.assign()
var data = [{
"SName": "Set1",
"Elements": [{
"Id": "3",
"Name": "Name1"
}, {
"Id": "5",
"Name": "Name2"
}]
}, {
"SName": "Set2",
"Elements": [{
"Id": "7",
"Name": "Name3"
}, {
"Id": "8",
"Name": "Name4"
}]
}]
var result = data.reduce(function(r, e) {
e.Elements.forEach(function(o) {
r.push(Object.assign({SName: e.SName}, o))
})
return r;
}, [])
console.log(result)
Here is solution using jQuery, here is jsfiddle:
https://jsfiddle.net/noitse/3uk9qjnf/
I hope you know all key names so it wont be problem to do it fixed.
var json = [
{
"SName": "Set1",
"Elements": [
{
"Id": "3",
"Name": "Name1"
},
{
"Id": "5",
"Name": "Name2"
}
]
},
{
"SName": "Set2",
"Elements": [
{
"Id": "7",
"Name": "Name3"
},
{
"Id": "8",
"Name": "Name4"
}
]
}
]
var newJSON = []
$(json).each(function(index,value){
$(value.Elements).each(function(index1,value1){
newJSON.push({"SName":value.SName,"Id":value1.Id,"Name":value1.Name})
})
})
alert(JSON.stringify(newJSON))
Here is code , what it does it loops through first JSON , then loops through its elements , then it push it to new array
You could use the $.extend method, which lets you create a copy of an object, while merging with another object.
var source = [] // Replace with the initalization of your source array
var destination = [];
for (var i = 0; i < source.length; i++) {
var node = source[i];
for (var j = 0; j < node.Elements.length; j++) {
var subNode = node.Elements[j];
newNode = $.extend(subNode, node);
delete newNode["Elements"];
destination.push(newNode);
}
}
You can run the code in this fiddle.
Here is my JSON code. I'm storing this json in an array.
{
"kind": "urlshortener#url",
"id": "http://goo.gl/2FIrtF",
"longUrl": "http://hike.com/?utm_source=facebook",
"status": "OK",
"created": "2015-09-22T13:45:53.645+00:00",
"analytics": {
"allTime": {
"shortUrlClicks": "1",
"longUrlClicks": "1",
"referrers": [
{
"count": "1",
"id": "unknown"
}
],
"countries": [
{
"count": "1",
"id": "IN"
}
],
"browsers": [
{
"count": "1",
"id": "Chrome"
}
],
"platforms": [
{
"count": "1",
"id": "Macintosh"
}
]
},
"month": {
"shortUrlClicks": "1",
"longUrlClicks": "1",
"referrers": [
{
"count": "1",
"id": "unknown"
}
],
"countries": [
{
"count": "1",
"id": "IN"
}
],
"browsers": [
{
"count": "1",
"id": "Chrome"
}
],
"platforms": [
{
"count": "1",
"id": "Macintosh"
}
]
},
"week": {
"shortUrlClicks": "1",
"longUrlClicks": "1",
"referrers": [
{
"count": "1",
"id": "unknown"
}
],
"countries": [
{
"count": "1",
"id": "IN"
}
],
"browsers": [
{
"count": "1",
"id": "Chrome"
}
],
"platforms": [
{
"count": "1",
"id": "Macintosh"
}
]
},
"day": {
"shortUrlClicks": "0",
"longUrlClicks": "0"
},
"twoHours": {
"shortUrlClicks": "0",
"longUrlClicks": "0"
}
},
"result": {
"kind": "urlshortener#url",
"id": "http://goo.gl/2FIuvF",
"longUrl": "http://hike.com/?utm_source=facebook",
"status": "OK",
"created": "2015-09-22T13:45:53.645+00:00",
"analytics": {
"allTime": {
"shortUrlClicks": "1",
"longUrlClicks": "1",
"referrers": [
{
"count": "1",
"id": "unknown"
}
],
"countries": [
{
"count": "1",
"id": "IN"
}
],
"browsers": [
{
"count": "1",
"id": "Chrome"
}
],
"platforms": [
{
"count": "1",
"id": "Macintosh"
}
]
},
"month": {
"shortUrlClicks": "1",
"longUrlClicks": "1",
"referrers": [
{
"count": "1",
"id": "unknown"
}
],
"countries": [
{
"count": "1",
"id": "IN"
}
],
"browsers": [
{
"count": "1",
"id": "Chrome"
}
],
"platforms": [
{
"count": "1",
"id": "Macintosh"
}
]
},
"week": {
"shortUrlClicks": "1",
"longUrlClicks": "1",
"referrers": [
{
"count": "1",
"id": "unknown"
}
],
"countries": [
{
"count": "1",
"id": "IN"
}
],
"browsers": [
{
"count": "1",
"id": "Chrome"
}
],
"platforms": [
{
"count": "1",
"id": "Macintosh"
}
]
},
"day": {
"shortUrlClicks": "0",
"longUrlClicks": "0"
},
"twoHours": {
"shortUrlClicks": "0",
"longUrlClicks": "0"
}
}
}
}
In the above JSON, how can we get the existence of analytics -> day -> countries?
I want to know whether the countries exists in day or not first, if it's not, show some value. If it is there, it will try to fetch the count of particualr country.
I'm trying this from last 5 hours without any luck.
if(arr.analytics.day.countries !== undefined) {
function thingscount(arr, platf) {
var x = arr.analytics.day.countries.map(function(el) {
return (platf.indexOf(el.id) != -1) ? parseInt(el.count) : 0; });
var count = 0;
for (var i = 0; i < x.length; i++) count += x[i];
return count;
}
var one = thingscount(arr, ["US"]);
}else{
var one = 0;
}
The above code is working fine if there is countries in day, but sometimes, in my JSON there will be no platforms part, in that case it's giving me
Uncaught TypeError: Cannot read property 'map' of undefined
I need a way to check if the platforms exist, if it's go for a count, if it's not give some other value to the variable.
UPDATE :
I'm using this below code to get the count of IN.
When it has IN key and value, it's giving me the result. But when it don't has the IN key, it's showing 'undefined count' error.
var month_inclicks = arr.analytics.month.countries.filter(function(el) { return el.id == "IN"; })[0].count;
How can we set a default value if the key we are looking for is not exists?
While that isn't JSON, I'm assuming it's a javascript object. That being said, you'll want to look into utilizing the hasOwnProperty method or the in keyword.
Example:
if (arr.total.limited.hasOwnProperty('platforms')) { //do stuff
or
if ('platforms' in arr.total.limited) { //do something
I have corrected your JSON. use hasOwnProperty as #CollinD suggested
var arr = {
total: {
limited: {
things: "451",
platforms: [{
count: "358",
id: "Windows"
}, {
count: "44",
id: "X11"
}, {
count: "42",
id: "Macintosh"
}, {
count: "2",
id: "Linux"
}, {
count: "1",
id: "iPhone"
}, {
count: "1",
id: "iPod"
}]
}
}
};
Object.prototype.hasOwnProperty()
console.log(arr.total.limited.hasOwnProperty('platforms'));
DEMO
For the record, you can roll the map and the count in your 'thingscount' function into one operation by using reduce:
var getCount = function getCount( ary, find ) {
return ary.reduce(function ( acc, record) {
if (find.indexOf(record.id) !== -1) acc += parseInt(record.count, 10);
return acc;
}, 0);
};
Usage inline:
if (arr.analytics.day.hasOwnProperty('countries')) {
var find = ['IN'],
count = arr.analytics.day.countries.reduce(function ( acc, record) {
if (find.indexOf(record.id) !== -1) acc += parseInt(record.count, 10);
return acc;
}, 0);
}
Or with the function:
if (arr.analytics.day.hasOwnProperty('countries')) {
var count = getCount(arr.analytics.day.countries, ['US','IN']);
}