looping through JSON object to get to the content of an array - javascript

I am breaking my head over this bit of code:
{
"Carrefour": [
{ "geography": [ "Europe", "Germany" ], "productLine": "Produce", "revenue": { "2022": 130143, "2021": 172122, "2020": 103716 } },
{ "geography": [ "Europe", "France" ], "productLine": "Clothing", "revenue": { "2022": 85693, "2021": 91790, "2020": 77650 } },
],
"Tesco": [
{ "geography": [ "Europe", "United Kingdom" ], "productLine": "Electronics", "revenue": { "2022": 239537, "2021": 131959, "2020": 97047 } },
{ "geography": [ "Europe", "Ireland" ], "productLine": "Produce", "revenue": { "2022": 74963, "2021": 43406, "2020": 54623 } },
]
}
I am trying to loop through this code to get to all the content.
But to begn with I don't know how to get to the region (Europe). I tried
function (json) {
for (var company in json) {
region = json[company].geography[0];
}
}
But it returns undefined, because company is an array. Infact json.Carrefour[0].geography[0]; returns correctly "Europe".
how do I access company as an array and retain the name? I can't use the name directly!
Thank you.

Your companies are assigned Arrays, so you need an inner loop.
for (var company in json) {
for (var i = 0; i < json[company].length; i++) {
region = json[company][i].geography[0];
}
}
Here's a demo: http://jsfiddle.net/dkPWt/
Demo output:
Carrefour:
Europe
Europe
Tesco:
Europe
Europe

Related

I'm beginner at Node JS trying to searching into JSON array using basic for loop, for iterating over array but not getting the desired results

I'm trying to search into json array using basic for loop, but not getting expected results. Please check what I'm missing.
Searching into json and want to get desired results on the basis of key:
json = [{
"web_pages": [
"https://www.iitbbs.ac.in/"
],
"name": "IIT Bhubaneswar",
"alpha_two_code": "IN",
"state-province": "Odisha",
"domains": [
"iitbbs.ac.in"
],
"country": "India"
},
{
"web_pages": [
"http://www.davietjal.org/"
],
"name": "DAV Institute of Engineering & Technology",
"alpha_two_code": "IN",
"state-province": "Punjab",
"domains": [
"davietjal.org"
],
"country": "India"
},
{
"web_pages": [
"https://www.sciencespo-rennes.fr/en/"
],
"name": "Institut d'études politiques de Rennes",
"alpha_two_code": "FR",
"state-province": null,
"domains": [
"sciencespo-rennes.fr"
],
"country": "France"
}
]
let count = 0;
for (let i = 0; i < json.length; i++) {
if (json[i] === "India") {
console.log(json[i]);
count++;
}
}
console.log(count);
You need to specify the place of this piece of data like json[i].country.
json = [{
"web_pages": [
"https://www.iitbbs.ac.in/"
],
"name": "IIT Bhubaneswar",
"alpha_two_code": "IN",
"state-province": "Odisha",
"domains": [
"iitbbs.ac.in"
],
"country": "India"
},
{
"web_pages": [
"http://www.davietjal.org/"
],
"name": "DAV Institute of Engineering & Technology",
"alpha_two_code": "IN",
"state-province": "Punjab",
"domains": [
"davietjal.org"
],
"country": "India"
},
{
"web_pages": [
"https://www.sciencespo-rennes.fr/en/"
],
"name": "Institut d'études politiques de Rennes",
"alpha_two_code": "FR",
"state-province": null,
"domains": [
"sciencespo-rennes.fr"
],
"country": "France"
}
]
let count = 0
for (var i = 0; i < json.length; i++) {
if (json[i].country === "India") {
console.log(json[i].name)
count++
}
}
console.log(count);

How can i group and restructure the JSON object in Angular8

I am getting below response, I want to ReGroup all the data and its children based on buSubRegion which is present inside children now. And also needs to add buSubRegion outside children.
For EX - In below Response, 1UL Africa belongs to Africa object and also present inside Europe object, so i need to merge children of all objects which belongs to 1UL Africa into one array of object.
I want if buSubRegion have a same value and it is present inside many objects then find all those objects and merge into one.
Also, Agbara - Savoury dont have a BU sub-region So i don't want to include this object.
Can anyone please help me to achieve this.
const data = [
{
"name": "Africa",
"id":1,
"children": [
{
"name": "Agbara - Laundry",
"buSubRegion": "1UL Africa",
"children": [
{
'lineId':"R_D005_TPKDST02"
}
]
},
{
"name": "Agbara - Savoury",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
}
]
},
{
"name": "Europe",
"id":2,
"children": [
{
"name": "Europe1",
"buSubRegion": "1UL Africa",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
},
{
"name": "Europe2",
"buSubRegion": "Test Europe",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
}
]
},
{
"name": "Latem",
"id":3,
"children": [
{
"name": "test1",
"buSubRegion": "latem1",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
}
]
}
];
Below is my Expected Output
[
{
"buSubRegion": "1UL Africa",
"name": "Africa",
"id":1,
"children": [
{
"name": "Agbara - Laundry",
"buSubRegion": "1UL Africa",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
},
{
"name": "Europe1",
"buSubRegion": "1UL Africa",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
}
]
},
{
"buSubRegion": "Test Europe",
"name": "Europe",
"id":2,
"children": [
{
"name": "Europe2",
"buSubRegion": "Test Europe",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
}
]
},
{
"name": "Latem",
"buSubRegion": "latem1",
"id":3,
"children": [
{
"name": "test1",
"buSubRegion": "latem1",
"children": [
{
"lineId":"R_D005_TPKDST02"
}
]
}
]
}
];
You can make use of reduce and inside that loop through children property to group the data by buSubRegion.
const data = [{"name":"Africa","id":1,"children":[{"name":"Agbara - Laundry","buSubRegion":"1UL Africa","children":[{"lineId":"R_D005_TPKDST02"}]},{"name":"Agbara - Savoury","children":[{"lineId":"R_D005_TPKDST02"}]}]},{"name":"Europe","id":2,"children":[{"name":"Europe1","buSubRegion":"1UL Africa","children":[{"lineId":"R_D005_TPKDST02"}]},{"name":"Europe2","buSubRegion":"Test Europe","children":[{"lineId":"R_D005_TPKDST02"}]}]},{"name":"Latem","id":3,"children":[{"name":"test1","buSubRegion":"latem1","children":[{"lineId":"R_D005_TPKDST02"}]}]}];
const result = data.reduce((a,{children, ...rest})=>{
children.forEach(({buSubRegion,...others})=>{
if(buSubRegion){
a[buSubRegion] ??= {buSubRegion, ...rest, children:[]};
a[buSubRegion].children.push({buSubRegion, ...others})
}
});
return a;
},{});
console.log(Object.values(result));

Creating custom json objects using changeable number of variables

I have this json object:
[
{
"trip": [
{
"place": {
"id": 8,
"name": "New York",
},
"group": 1
}
},
...
]
I can have a N number of groups, so i need to create an array of objects like this:
[
{
"group1": "New York",
"group2": "Los Angeles",
"group3": "Rome",
...
}
]
Each group is called groupX where X is a number taken from every "group" instance in every object in the first array and his value must be taken from "name" instance in every object in the first array.
How can i do it? Thanks in advance!
.map() is handy for getting an array of results, applying a function to each element of an existing array. Something like this:
var obj = [{
"trip": [{
"place": {
"id": 8,
"name": "New York",
},
"group": 1
}]
},
{
"trip": [{
"place": {
"id": 8,
"name": "london",
},
"group": 2
}]
},
{
"trip": [{
"place": {
"id": 8,
"name": "tokyo",
},
"group": 3
}]
},
]
var result = obj.map((array_element) => {
let group = "group" + String(array_element['trip'][0]['group'])
let place = String(array_element['trip'][0]['place']['name'])
let to_return = {};
to_return[group] = place
return to_return;
})
console.log(result)
/*
[
{ "group1": "New York" },
{ "group2": "london" },
{ "group3": "tokyo" }
]
*/
You can do it like this:
let data = [
{ 'trip': [{ 'place': { 'id': 8, 'name': 'New York' }, 'group': 1 }] },
{ 'trip': [{ 'place': { 'id': 9, 'name': 'Los Angeles' }, 'group': 2 }] },
{ 'trip': [{ 'place': { 'id': 10, 'name': 'Rome' }, 'group': 3 }] },
]
let grouped = data.reduce(function(grouped, current) {
grouped['group' + current.trip[0].group] = current.trip[0].place.name;
return grouped;
}, {})
console.log(grouped);

traversing through JSON string to inner levels using recursive function

I have a JSON input which can go to any number of levels.
I'm giving an input sample of
var d=getEntities( {"Categories":
{
"Facets":
[
{
"count": 1,
"entity": "Company",
"Company":
[
{
"entity": "Ford Motor Co",
"Ford_Motor_Co":
[
{
"count": 1,
"entity": "Ford"
}
]
}
]
},
{
"count": 4,
"entity": "Country",
"Country": [
{
"entity": "Germany",
"Germany": [
{
"count": 1,
"entity": "Germany"
}
],
"currency": "Euro (EUR)"
},
{
"entity": "Italy",
"Italy": [
{
"count": 1,
"entity": "Italy"
}
],
"currency": "Euro (EUR)"
},
{
"entity": "Japan",
"Japan": [
{
"count": 1,
"entity": "Japan"
}
],
"currency": "Yen (JPY)"
},
{
"entity": "South Korea",
"South_Korea": [
{
"count": 1,
"entity": "South Korea"
}
],
"currency": "Won (KRW)"
}
]
},
{"count": 5,
"entity": "Persons",
"Persons": [
{
"count": 2,
"entity": "Dodge"
},
{
"count": 1,
"entity": "Dodge Avenger"
},
{
"count": 1,
"entity": "Major League"
},
{
"count": 1,
"entity": "Sterling Heights"
}
]
}
]
}});
I want to add the key value "Entity" in all levels to an array using recursion,
I'm able to collect the data from first level using the string
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript" src="dataDumper.js"></script>
<script type="text/javascript">
var testJSON = {"Categories":
{
"Facets":
[
{
"count": 1,
"entity": "Company",
"Company":
[
{
"entity": "Ford Motor Co",
"Ford_Motor_Co":
[
{
"count": 1,
"entity": "Ford"
}
]
}
]
},
{
"count": 4,
"entity": "Country",
"Country": [
{
"entity": "Germany",
"Germany": [
{
"count": 1,
"entity": "Germany"
}
],
"currency": "Euro (EUR)"
},
{
"entity": "Italy",
"Italy": [
{
"count": 1,
"entity": "Italy"
}
],
"currency": "Euro (EUR)"
},
{
"entity": "Japan",
"Japan": [
{
"count": 1,
"entity": "Japan"
}
],
"currency": "Yen (JPY)"
},
{
"entity": "South Korea",
"South_Korea": [
{
"count": 1,
"entity": "South Korea"
}
],
"currency": "Won (KRW)"
}
]
},
{"count": 5,
"entity": "Persons",
"Persons": [
{
"count": 2,
"entity": "Dodge"
},
{
"count": 1,
"entity": "Dodge Avenger"
},
{
"count": 1,
"entity": "Major League"
},
{
"count": 1,
"entity": "Sterling Heights"
}
]
}
]
}};
function scan(obj)
{
var k;
if (obj.hasOwnProperty('entity')) {
for (k in obj){
if (obj.hasOwnProperty(k)){
scan( obj[k] );
}
}
}
else{
if(k=='entity')
{
alert(obj.entity);
}
}
};
scan(testJSON);
</script>
</head>
<body>
</body>
</html>
How do I get in to the inner levels for JSON string using recursive functions?
I have made a jsfiddle which traverses every object,array and value in the JS object like so...
function scan(obj) {
var k;
if (obj instanceof Object) {
for (k in obj){
if (obj.hasOwnProperty(k)){
//recursive call to scan property
scan( obj[k] );
}
}
} else {
//obj is not an instance of Object so obj here is a value
};
};
I get no recursion error (in Chrome). Can you use this to do what you want?
If you need to test if an object is an array use if (obj instanceof Array)
To test if an object has an "entity" property use if (obj.hasOwnProperty('entity'))
To add (or modify an existing) "entity" property use obj.entity = value or obj['entity'] = value
(function recur( obj ) {
Object.keys( obj ).forEach( function( prop ) {
// Check if the property is an object
if ( ({}).toString.apply( prop ) === '[object Object]' ) {
// If it is, recall this function
recur( prop );
}
} );
} () );
I haven't added your logic, but you get the idea of how to recursively traverse your object.
Say I have a structure like the following:
var aObject = {
items: [],
children: {}
}
Children is an associative array that contains more aObjects. So it could look like this:
var aObject = {
items: [],
children: {
"subgroup1": {
items: [],
children: {}
},
"subgroup2": {
items: [],
children: {}
}
}
}
I have an item that contains an array of subgroups:
["subgroup1", "subgroup1a"]
Each subgroup is a 'location'. The item needs to be placed at:
aObject.children[array[0]].children[array[1]].items
At each level, we have to check if children[array[i]] exists, and if not, create it. You can't simply write aObject.children[array[0]].children[array[1]].items.push(item) because children[array[0]] might not already exist and we will get an error.
This can be solved using recursion! (AngularJS)
function recursive(aLevel, aItem, aArray, aIndex){
var lLevel = aLevel;
// If we have reached the end of the array
if (aIndex === aArray.length){
// Insert
aLevel.items.push(aItem);
} else {
// If the subgroup doesn't exist, create it
if (typeof aLevel.children[aArray[aIndex]] === 'undefined'){
aLevel.children[aArray[aIndex]] = {
items: [],
children: {}
};
}
// Move into
recursive(aLevel.children[aArray[aIndex]], aItem, aArray, aIndex+1);
}
}
aObject = {
items: [],
children: {},
}
angular.forEach(items, function(item, i){
var location = item.location;
if (location.length == 0){
aObject.items.push(item);
} else {
recursive(aObject, item, location, 0);
}
});
The final aObject would look like this:
var aObject = {
items: [],
children: {
"subgroup1": {
items: [],
children: {
"subgroup1a": {
items: [item],
children: {}
}
}
},
"subgroup2": {
items: [],
children: {}
}
}
}
Here is a function that i use often. It's easily modifiable to do many recursive tasks. For example if you add a bail flag you can quickly get the stack or add a callback function that makes it even more general. Anyway that's my 2 cents
var recursiveObjMap = (function(){
var stack = [];
var result = [];
// var bail = false;
return function map(data, key){
if (!$.isArray(data) && !$.isPlainObject(data) ) {
result.push(data);
return false
}
$.each(data, function(i, v){
if (key) stack.push(key);
map(v, i);
stack.pop();
});
return result;
};
})();
recursiveObjMap({a:'b',c:{d:{e:"f"}}}) // ['b', 'f']
const obj = [
{
count: 1,
entity: "Company",
Company: [
{
entity: "Ford Motor Co",
Ford_Motor_Co: [
{
count: 1,
entity: "Ford",
},
],
},
],
},
{
count: 4,
entity: "Country",
Country: [
{
entity: "Germany",
Germany: [
{
count: 1,
entity: "Germany",
},
],
currency: "Euro (EUR)",
},
{
entity: "Italy",
Italy: [
{
count: 1,
entity: "Italy",
},
],
currency: "Euro (EUR)",
},
{
entity: "Japan",
Japan: [
{
count: 1,
entity: "Japan",
},
],
currency: "Yen (JPY)",
},
{
entity: "South Korea",
South_Korea: [
{
count: 1,
entity: "South Korea",
},
],
currency: "Won (KRW)",
},
],
},
{
count: 5,
entity: "Persons",
Persons: [
{
count: 2,
entity: "Dodge",
},
{
count: 1,
entity: "Dodge Avenger",
},
{
count: 1,
entity: "Major League",
},
{
count: 1,
entity: "Sterling Heights",
},
],
},
];
function test(runObj) {
for (let i in runObj) {
typeof runObj[i] == "object" ? test(runObj[i]) : console.log(runObj[i]);
}
}
test(obj);

take JSON input and store it in to an array (javascript)

I have a JSON input of
{
"Categories": {
"Facets": [{
"count": 1,
"entity": "Company",
"Company": [{
"entity": "Ford Motor Co",
"Ford_Motor_Co": [{
"count": 1,
"entity": "Ford"
}]
}]
}, {
"count": 4,
"entity": "Country",
"Country": [{
"entity": "Germany",
"Germany": [{
"count": 1,
"entity": "Germany"
}],
"currency": "Euro (EUR)"
}, {
"entity": "Italy",
"Italy": [{
"count": 1,
"entity": "Italy"
}],
"currency": "Euro (EUR)"
}, {
"entity": "Japan",
"Japan": [{
"count": 1,
"entity": "Japan"
}],
"currency": "Yen (JPY)"
}, {
"entity": "South Korea",
"South_Korea": [{
"count": 1,
"entity": "South Korea"
}],
"currency": "Won (KRW)"
}]
}, {
"count": 5,
"entity": "Persons",
"Persons": [{
"count": 2,
"entity": "Dodge"
}, {
"count": 1,
"entity": "Dodge Avenger"
}, {
"count": 1,
"entity": "Major League"
}, {
"count": 1,
"entity": "Sterling Heights"
}]
}]
}
}
I need to get the values for entity in each level in to an array..
[Company, Ford Motor Co, Ford, ....... , Sterling Heights]
I am able to get thru the first level with the code
for (var k in h.Categories.Facets)
{
alert(h.Categories.Facets[k].entity);
}
How do I reach thru the innerlevels to get the values of entity??
You should do a foreach on each entity. If you know how many levels there are you can nest loops. If not - probably should go for a recursive function.
Edit
Recursive function:
function getEntities(ent)
{
alert(ent);
for (var l in ent)
{
getEntities(ent[l].entity);
}
}
Then use:
for (var k in h.Categories.Facets)
{
getEntities(h.Categories.Facets[k]);
}
Good luck!
The most general recursive answer:
function getEntities(any) {
var entities = [];
if ('entity' in any​) {
entities.push(any.entity);
}
for (var prop in any) {
if (any[prop] instanceof Object && any.hasOwnProperty(prop)) {
entities.append(getEntities(any[prop]));
}
}
return entities;
}
console.log(getEntities(h));
The line:
if (any[prop] instanceof Object && any.hasOwnProperty(prop)) {
Keeps numbers/nulls from bombing and the any.hasOwnProperty(prop) makes up for frameworks that like to attach to the Object prototype.
One way is to write a recursive method that accepts an array and extracts the methods from it.
As suggested, you can use a recursive function to loop through every possible nested combo:
var allEntities = [];
function getEntities(obj)
{
if (obj != null)
{
var entityName = obj["entity"];
alert(entityName);
if (entityName != null)
{
allEntities.push(entityName);
var adjName = entityName.replace(/ /gi, "_");
var entities = obj[adjName];
if (entities != null)
{
for (var e in entities)
{
var innerEntities = getEntities(entities[e]);
for (var inner in innerEntities)
allEntities.push(innerEntities[inner]);
}
}
}
}
}
for (var k in h.Categories.Facets)
{
alert(h.Categories.Facets[k].entity);
getEntities(h.Categories.Facets[k]);
}
alert(allEntities.length);

Categories

Resources