How can I remap one JSON lines to hierachycal JSON? - javascript

I am meeting now the difficult problem for me that hurt my heart,
I want to convert [01] JSON to [02].
[01] JSON :
{locations: [
{
country: "Australia",
area: "NSW",
city: "Gordon"
},
{
country: "Australia",
area: "NSW",
city: "Chatswood"
}
]};
[02] JSON :
{countries: [
{
name: "Australia",
areas: [
{
name: "NSW",
cities: [
{
name: "Gordon"
},
{
name: "Chatswood"
}
]
}
]
}
]}

Since you're going to be doing a bunch of lookups I suggest using a collection of objects rather than your final structure with arrays. You can then either convert it to the final structure or modify code to use it the way it is.
var countries = {};
for (var i=0, loc; loc = locations[i]; i++) {
if (!countries[loc.country]) countries[loc.country] = {};
if (!countries[loc.country][loc.area]) countries[loc.country][loc.area] = [];
countries[loc.country][loc.area].push(loc.city);
}
alert(JSON.stringify(countries));

Related

JSON data in js object into html list

I have a json file converted into a js object
var factory = {
city: "turin",
street: "corso unione sovietica",
nAddres: 74,
operative: true,
models: ["toyota", "chevrolet", "ford", "subaru", "honda"],
workspace: {
offices: 12,
minsOfPause: 15,
},
cars: {
toyota: {
id: 1,
numberPlate: "S4IIPLE",
broken: false,
insurance: null,
previousOwners: ["Mark", "Sebastian", "Carlos"],
infos: {
parketAt: "425 2nd Street",
city: "San Francisco",
state: "CA",
postalCode: 94107,
},
},
chevrolet: {
id: 2,
numberPlate: "S2IALR",
broken: true,
insurance: null,
previousOwners: ["Robert", "Mark"],
infos: {
parketAt: "711-2880 Nulla St",
city: "Mankato",
state: "MS",
postalCode: 96522,
},
},
},
};
var json = JSON.stringify(factory);
json = JSON.parse(json);
I have to display the data in a ul li list in an HTML file but when I try to iterate the objects with
for(var a in json){
console.log(a);
}
the console says that the object is not iterable
and with
for(var a of json){
console.log(a);
the console doesn't display the value
pls help
A for...of loop is used to loop through an array.
For an object, we should use for...in loop.
Here, it should be :
for (let a in json){
console.log(a);
}

Finding commonality in object days

I have an array of objects where I want to find out what consecutive days are the most common between all of them and then choose the first day of that consecutive day pair.
let data = [
{
name: "mike",
city: "Los Angeles",
days: ["2020-01-02", "2020-01-03","2020-01-18", "2020-01-19"]
},
{
name: "Kenny",
city: "Chicago",
days: ["2020-04-02", "2020-04-12","2020-04-19"]
},
{
name: "James",
city: "Los Angeles",
days: ["2020-05-02", "2020-05-12","2020-05-19"]
},
{
name: "Maggie",
city: "Los Angeles",
days: ["2020-11-12", "2020-11-13","2020-05-19"]
},
{
name: "Ricardo",
city: "Los Angeles",
days: ["2020-01-02", "2020-01-03","2020-05-19"]
},
{
name: "Reeny",
city: "Chicago",
days: ["2020-01-02", "2020-01-04","2020-05-09"]
},
];
so for example, for Los Angeles, I'd want to return:
{
city: "Los Angeles",
day: "2020-01-02",
people: ["mike", "ricardo"],
}
"Maggie" wouldn't be in since her available consecutive days appear less than Mike and James.
For Mike and James, "2020-01-02" and "2020-01-03" appears most for Los Angeles.
For Chicago, I'd want to return just an empty string since I don't have any consecutive days.
So far, I iterated through the data and pushed the city to an object. If the city is already in the object, I push each day to the existing array. If the city is not in the hash object, then I just set it and have it equal the days
let obj = {};
data.forEach(x => {
if (map[x.city]) {
x.days.forEach(y => {
map[x.city].push(y);
})
} else {
map[x.city] = x.days;
}
});
for (x in obj) {
let arr = [...new Set(obj[x])]
obj[x] = arr.sort();
}
my result is an object with the city as a key and the value is the days (with the duplicates removed via Set) :
obj = {
"Los Angeles": ["2020-01-02", "2020-01-03","2020-01-18", "2020-01-19", "2020-05-02", "2020-05-12","2020-05-19", "2020-11-12", "2020-11-13"],
"Chicago": ["2020-01-02", "2020-01-04","2020-04-02", "2020-04-12","2020-04-19", "2020-05-09"]
}
From this point, I'm not sure what to do. I imagine it's possible to accomplish this but I don't know the next step here.
You can use alasql
https://github.com/agershun/alasql/wiki/Examples
with alasql can you make: DISTINCT or GROUP etc.
example:
// Fill table with data
var person = [
{ name: 'bill' , sex:'M', income:50000 },
{ name: 'sara' , sex:'F', income:100000 },
{ name: 'larry' , sex:'M', income:90000 },
{ name: 'olga' , sex:'F', income:85000 },
];
// Do the query
var res = alasql("SELECT * FROM ? person WHERE sex='F' AND income > 60000", [person]);
document.getElementById("result").innerHTML = JSON.stringify(res);

In plain Javascript, trying to filter for multiple values in an array that contains User objects that contain other objects and arrays

thanks for taking a look at this. Sorry for length, trying to be clear!
WHAT I'M TRYING TO DO:
I have an array of users (each user an object) and am trying to filter the users on multiple criteria ("males from France" OR "females from Spain and United States with Engineering skills" etc) but it's proven beyond my skills so far.
The hard part has been that the users are objects within a User array, but within each user object, some values are additional objects or arrays. Here's what the user data array looks like (abbreviated):
let users = [
{
gender: 'male',
location: {street: 'Clement Street', country: 'United States'},
skills: ['engineering', 'underwater'],
}, ...
Notice gender is just a normal property/value but country is within a location object and skills are within an array.
I already have a search button interface that creates toggle buttons to search on each criteria available, and every time you click a button, I add or remove that criteria in a filter object. The filter object looks like this, and uses arrays inside it so that I can define multiple criteria at once, like multiple countries to search, multiple skills, etc.:
filter: {
gender: ['female'],
location: {
country: ['Spain'],},
skills: ['optics', ]
},
WHERE I REALLY GET STUCK
I've created a filterData method that can successfully filter based on Gender (male or female) but can't get it to ALSO filter on country (within the location object) or skills (within the skills array). My current filterData method only goes through one iteration per user, but I've tried For loops and forEach to try to go through each of the filter's criteria ('Spain', 'Optics'), but it just doesn't work. I only get gender.
I think I have two problems: 1) somehow conveying in the code that the item 'key' in some cases will not be a value, but an object or array that must also be searched within, and 2) creating some kind of looping behavior that will go through each of the filter criteria, instead of stopping after the first one (gender).
That's apparently over my head right now, so any guidance or suggestions would be appreciated, thanks very much! And here's all the code I've been working with, including my filterData method.
var filtering = {
filter: {
gender: ["female"],
location: {
country: ["Spain"],
},
skills: ["optics"],
},
users: [
{
gender: "male",
name: "John",
location: { street: "Clement Street", country: "United States" },
skills: ["engineering", "underwater"],
},
{
gender: "female",
name: "Mary",
location: { street: "5th Avenue", country: "Spain" },
skills: ["confidence", "optics"],
},
{
gender: "male",
name: "David",
location: { street: "Vermont Ave", country: "France" },
skills: ["cards", "metalurgy", "confidence"],
},
{
gender: "female",
name: "Rachel",
location: { street: "Vermont Ave", country: "France" },
skills: ["disguise", "electrical"],
},
{
gender: "female",
name: "Muriel",
location: { street: "Vermont Ave", country: "Germany" },
skills: ["flight", "surveillance"],
},
],
filterData: (filter) => {
const filteredData = filtering.users.filter((item) => {
for (let key in filter) {
if (!filter[key].includes(item[key])) {
return false;
}
return true;
}
});
console.log(filteredData);
},
};
filtering.filterData(filtering.filter);
There's a nifty trick called recursion, which is a function calling itself.
The updated code are: checkUserand
filterData
var filtering = {
filter: {
gender: ["female"],
location: {
country: ["Spain"],
},
skills: ["optics"],
},
users: [
{
gender: "male",
name: "John",
location: { street: "Clement Street", country: "United States" },
skills: ["engineering", "underwater"],
},
{
gender: "female",
name: "Mary",
location: { street: "5th Avenue", country: "Spain" },
skills: ["confidence", "optics"],
},
{
gender: "male",
name: "David",
location: { street: "Vermont Ave", country: "France" },
skills: ["cards", "metalurgy", "confidence"],
},
{
gender: "female",
name: "Rachel",
location: { street: "Vermont Ave", country: "France" },
skills: ["disguise", "electrical"],
},
{
gender: "female",
name: "Muriel",
location: { street: "Vermont Ave", country: "Germany" },
skills: ["flight", "surveillance"],
},
],
checkUser (filter, to_check) {
if (Array.isArray(filter))
{
return Array.isArray(to_check)
? filter.some(val => to_check.includes(val)) // if what we're checking is an array
: filter.includes(to_check); // otherwise it's a singular value
}
else
{
const all_checks = []; // this is to save every return value from the recursive function
for (let key in filter) // going through each key in the filter
{
const checked = this.checkUser(filter[key], to_check[key]) // passing two values, which will be compared with each other
all_checks.push(checked) // pushing the checked result
}
return all_checks.every(val => val) // checking that it passes the filter by ensuring every value is true
}
},
filterData () {
let filter = this.filter
return this.users.filter(user => this.checkUser(filter, user))
},
};
// filtering.filterData(filtering.filter);
// filtering.checkUser(filtering.filter, filtering.users[0])
const result = filtering.filterData()
console.log(result)
Bit complex data structure, you should clean. However, solved what expected.
const mergeFilter = (item, [key, value]) => {
let val = Array.isArray(item[key]) ? item[key] : [item[key]];
let m = value[0];
if (typeof value === "object" && !Array.isArray(value)) {
const k2 = Object.keys(value);
val = item[key][k2];
m = value[k2][0];
}
return val.includes(m);
};
const filterData = (users, filter) => {
const filters = Object.entries(filter);
const result = users.reduce((arr, item) => {
let found = filters.every(mergeFilter.bind(null, item));
if (found) arr.push(item);
return arr;
}, []);
return result;
};
var filtering = {"filter":{"gender":["female"],"location":{"country":["Spain"]},"skills":["optics"]},"users":[{"gender":"male","name":"John","location":{"street":"Clement Street","country":"United States"},"skills":["engineering","underwater"]},{"gender":"female","name":"Mary","location":{"street":"5th Avenue","country":"Spain"},"skills":["confidence","optics"]},{"gender":"male","name":"David","location":{"street":"Vermont Ave","country":"France"},"skills":["cards","metalurgy","confidence"]},{"gender":"female","name":"Rachel","location":{"street":"Vermont Ave","country":"France"},"skills":["disguise","electrical"]},{"gender":"female","name":"Muriel","location":{"street":"Vermont Ave","country":"Germany"},"skills":["flight","surveillance"]}]}
const result = filterData(filtering.users, filtering.filter);
console.log(result)

Using map in a multidimensional array Javascript

I have this set of data that I'm trying to convert to map:
x = [
{
food: 'Steak',
ingredients: [
{
item1: 'pepper',
},
{
item2: "salt",
},
],
},
{
food: 'Veggies'
},
{
food: 'Fruits'
},
];
This is my current map function, question is how do I iterate on the ingredients?:
<div>
{Object.keys(x).map(key => (
<a key={key}>{x[key].food}</a>
))}
</div>
Something like this?
x = [
{
food: 'Steak',
ingredients: [
{
item1: 'pepper',
},
{
item2: "salt",
},
],
},
{
food: 'Veggies'
},
{
food: 'Fruits'
},
];
const list = x.map(item =>
({[item.food]: item.ingredients ?
item.ingredients.flatMap(i =>
Object.keys(i).map(k =>
i[k])).join(','): 'no ingredients'}))
console.log(list)
Output:
[
{
"Steak": "pepper,salt"
},
{
"Veggies": "no ingredients"
},
{
"Fruits": "no ingredients"
}
]
A better format for the data:
x = [
{
food: 'Steak',
ingredients: [
"pepper", "salt",
],
},
{
food: 'Veggies'
},
{
food: 'Fruits'
},
];
Naming things is 80% of programming. The other 20% is choosing the right font for your IDE.
If you have an array of objects and the key of object holds no semantic meaning, and there is one key in each object, that's a sign that it should be an array.
You could go one step further:
const ingredients = {
Steak: ["pepper", "salt"],
Veggies: []
Fruits: []
};
The name of the data structure makes sense. It is an "ingredients by food" object.
Where you went off is starting with x as the name of the object. x is an unknown. Start by describing everything clearly, and use JetBrains Mono.
If you want to easily iterate over the object using map (like to render a table in React), then you could do:
const ingredients = [
{Steak: ["pepper", "salt"]},
{Veggies: []},
{Fruits: []}
];
or:
const recipes = [
{food: Steak, ingredients: ["pepper", "salt"]},
{food: Veggies, ingredients: []},
{food: Fruits, ingredients: []}
];
(which is close to the reduction I did to your original data)
That one should be called recipes, which I discovered when I wrote this next function and the names didn't make sense if the object were named ingredients.
recipes.forEach(recipe => {
console.log(`HTML Title: %{recipe.food})
console.log(`HTML Subtitle: Ingredients`)
recipe.ingredients.forEach(ingredient =>
console.log(`* ${ingredient}`)
)
})
See, the names in the data structure make sense, and so do the functions to work with it. And the data structure itself is small and comprehensible. Structure is also data.
JetBrains Mono.
You can store all ingredientItem in one array and then apply Map on that array:
let ingredientItem = [];
x.forEach((item) => {
if (item.ingredients) {
item.ingredients.forEach((ingredient) => {
for (name in ingredient) {
ingredientItem.push(ingredient[name])
}
})
}
})
ingredientItem.map((item) => {
})

How to format multiple JSON objects in an Array

I want to have a JSON object which contains multiple person objects. Is there a better way to format this? What I did below is have a result key which would be an array consisting of arrays (which have the JSON person object inside of the inner array).
{
result: [
[
{
"name": "Josh",
"age": 15
}
],
[
{
"name": "Joe",
"age": 16
}
]
]
}
Then in the for loop I do something like this:
var nameArray = result[0];
for (var i = 0; i < numberOfObjectsInJSONObject; i++) {
newNameArray.push(nameArray[i].firstPerson);
}
No point in having each person object wrapped inside it's own array. Unless there is some other grouping that needs done all you should need is one array that contains all the person objects
result: [
{
"name": "Josh",
"age": 15
},
{
"name": "Joe",
"age": 16
}
]
This array can be sorted by ages or names, filtered etc
If you want to keep object like that, something like this work. pleases try this one
var pList = {
people: [{
'name': 'Josh',
'age': 15
}, {
'name': 'Joe',
'age': 16
}],
animal: [{
'type': 'Dog',
'legs': 4
}, {
'type': 'Bird',
'legs': 2
}]
};
[].forEach.call(pList.people, function(p) {
// can push its value into new array or else
console.log(`${p.name} -- ${p.age}`);
})
//or
pList.animal.forEach(function(a) {
console.log(`${a.type} -- ${a.legs}`)
})
Here is your list of objects:
var a = [];
a.push({ "name" : "Joe", "age" : 16 });
a.push({ "name" : "John", "age" : 17 });
Here is how you can create JSON:
JSON.stringify(a);
Here is the result:
[{"name":"John","age":17},{"name":"Joe","age":16}]
Here is how you can iterate through your array:
for (var i = 0; i < a.length; i++) { console.log(a[i]) }

Categories