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
Related
In vanilla JavaScript, how would I find unique locations from this object and make them keys, and place all items with that location as values. (can install lodash if necessary).
So this:
[
{
"item": {
"id": "cat"
},
"location": {
"id": "porch"
}
},
{
"item": {
"id": "dog"
},
"location": {
"id": "porch"
}
},
{
"item": {
"id": "snake"
},
"location": {
"id": "forest"
}
},
{
"item": {
"id": "bird"
},
"location": {
"id": "forest"
}
},
{
"item": {
"id": "beer"
},
"location": {
"id": "fridge"
}
}
]
Becomes this:
[
{
"porch": [
{
"id": "cat"
},
{
"id": "dog"
}
]
},
{
"forest": [
{
"id": "snake"
},
{
"id": "bird"
}
]
},
{
"fridge": [
{
"id": "beer"
}
]
}
]
PEN
// modified desired result
[
{
"location": {
"name": "porch",
"items": [
{
"title": "cat"
},
{
"title": "dog"
}
]
}
},
{
"location": {
"name": "forest",
"items": [
{
"title": "snake"
},
{
"title": "bird"
}
]
}
},
{
"location": {
"name": "fridge",
"items": [
{
"title": "beer"
}
]
}
}
]
let obj = [
{
"item": {
"id": "cat"
},
"location": {
"id": "porch"
}
},
{
"item": {
"id": "dog"
},
"location": {
"id": "porch"
}
},
{
"item": {
"id": "snake"
},
"location": {
"id": "forest"
}
},
{
"item": {
"id": "bird"
},
"location": {
"id": "forest"
}
},
{
"item": {
"id": "beer"
},
"location": {
"id": "fridge"
}
}
]
let result = {};
obj.forEach(({item, location}) => {
if(!result[location.id]) result[location.id] = []
result[location.id].push({title: item.id})
})
result = Object.keys(result).map(key => ({
"location": {
"name": key,
"items": result[key]
}
}))
result contains required output.
I have the following nested array of objects:
[
{
"info": [
{
"period": {
"start": "2020-01-01",
"end": "2020-01-31"
},
"info": [
{
"id": 036,
"name": "john",
},
{
"id": 037,
"name": "inna",
}
]
}
]
},
{
"info": [
{
"period": {
"start": "2020-01-01",
"end": "2020-01-31"
},
"info": [
{
"id": 045,
"name": "carl",
},
{
"id": 056,
"name": "tina",
}
]
}
]
}]
I want to extract all the values of the "name" property and put them in an array.
Output: ["john", "inna", "carl", "tina"].
Try with this code:
const userNames = [];
data.map(item => {
return item.info.map(registry => {
return registry.info.map(user => userNames.push(user.name));
})
})
Output: ["john", "inna", "carl", "tina"]
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
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>
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']);
}