JSON data in js object into html list - javascript

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);
}

Related

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)

unable to access fields in json objects from an array of json objects

This is the array of JSON objects I get when I am doing a query on MongoDB using Mongoose library. I am getting a response in the form of an array. Now I am trying to generate the customised JSON object and send it across as a response
[{
_id: 5 c759f301b164e139f2df980,
Sno: 1,
MaterialName: 'Material1',
MaterialId: '0000000000000000ABCDA001',
LocationName: 'RWH_S1_SZ_AL1',
LocationId: '00000000000000001111A001',
Quantity: '50',
DeliveryLocationName: 'IN4_SEC1',
DeliveryLocationID: '00000000000000003333C001',
PickedUp: 'Yes/No(1/0)',
PickTimeStamp: null,
Delivered: 'Yes/No(1/0)',
DeliveryTimeStamp: null
},
{
_id: 5 c759f301b164e139f2df981,
Sno: 2,
MaterialName: 'Material2',
MaterialId: '0000000000000000ABCDB001',
LocationName: 'RWH_S1_SZ_AL2',
LocationId: '00000000000000001111A001',
Quantity: '10',
DeliveryLocationName: 'IN4_SEC1',
DeliveryLocationID: '00000000000000003333C001',
PickedUp: null,
PickTimeStamp: null,
Delivered: null,
DeliveryTimeStamp: null
},
{
_id: 5 c759f301b164e139f2df982,
Sno: 3,
MaterialName: 'Material3',
MaterialId: '0000000000000000ABCDC001',
LocationName: 'RWH_S1_SZ_AL3',
LocationId: '00000000000000002222B001',
Quantity: '30',
DeliveryLocationName: 'IN4_SEC1',
DeliveryLocationID: '00000000000000003333C001',
PickedUp: null,
PickTimeStamp: null,
Delivered: null,
DeliveryTimeStamp: null
}]
I am getting this array as a response(resp) to a MongoDB query using mongoose.
Now I am trying to generate customized JSON objects by accessing the fields from the received JSON objects array.so when I am doing like this below here 5 is no of objects in the JSON array
for (var i = 0; i <= 5; i++) {
var json = {
LINE1: "MaterialName": resp[i].MaterialName,
"MaterialId": resp[i].MaterialId,
"LocationName": resp[i].LocationName,
"LocationId": resp[i].LocationId,
"Quantity": resp[i].Quantity,
"DeliveryLocationName": resp[i].DeliveryLocationName,
"DeliveryLocationId": resp[i].DeliveryLocationId
}
}
Type error comes up and says property 0 not defined at LINE1 is there a problem with accessing the array this way. What should I do now? please help me.
Your main problem is that this syntax is not valid:
var json = {
LINE1: "foo": "bar", "lala": "lolo"
}
.as-console {background-color:black !important; color:lime;}
You need to declare the LINE1 key as an object, like this:
var json = {
LINE1: {"foo": "bar", "lala": "lolo"}
}
console.log(json);
.as-console {background-color:black !important; color:lime;}
So, your code should be reworked like this:
var json;
for (var i = 0 ; i <= 5 ; i++)
{
json = {
LINE1: {
"MaterialName": resp[i].MaterialName,
"MaterialId": resp[i].MaterialId,
"LocationName": resp[i].LocationName,
"LocationId": resp[i].LocationId,
"Quantity": resp[i].Quantity,
"DeliveryLocationName": resp[i].DeliveryLocationName,
"DeliveryLocationId": resp[i].DeliveryLocationId
}
}
// TODO: Do something with json variable or will be
// overwrite by next iterations.
}
You can do something like this. Assuming the large JSON you shared here (coming from MongoDB) is present in resp variable.
var resp = [{}]; //This is your large array coming from MongoDB.
function getCustomJsonObject(resp){
var outputArray = [];
for(var i=0; i< resp.length; i++){
var jsonObj = {
"MaterialName": resp[i].MaterialName,
"MaterialId": resp[i].MaterialId,
"LocationName": resp[i].LocationName,
"LocationId": resp[i].LocationId,
"Quantity": resp[i].Quantity,
"DeliveryLocationName": resp[i].DeliveryLocationName,
"DeliveryLocationId": resp[i].DeliveryLocationId
}
outputArray.push(jsonObj);
}
return outputArray;
}
var customObj = getCustomJsonObject(resp);

Get specific value from json [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 5 years ago.
I have this json. I only care about the uniqueIDs.
How can I get ONLY the uniqueID values delivered back to me as a comma separated list, ie, 11111, 22222? (I need to create my own array.) I can't edit the json below - I am just trying to parse the value I care about out of it....
{
products: [{
type: "Unique",
name: "Joe",
description: "Joes Description",
uniqueID: "11111"
}, {
type: "Unique",
name: "Jane",
description: "Janes Description",
uniqueID: "22222"
}]
}
Thought it would be this easy but its not...
$data['uniqueID'][0]
Use map function:
var foo = {
metadata: {
products: [{
type: "Unique",
name: "Joe",
description: "Joes Description",
uniqueID: "11111"
} {
type: "Unique",
name: "Jane",
description: "Janes Description",
uniqueID: "22222"
}]
}
}
var ids = foo.metadata.products.map(x => x.uniqueID);
And if you are not familiar with arrow function:
var ids = foo.metadata.products.map(function(x){
return x.uniqueID;
});
The Underscore Way
You can use underscore js _.pluck() or _.map() function.
var data = {
metadata: {
products: [{
type: "Unique",
name: "Joe",
description: "Joes Description",
uniqueID: "11111"
},
{
type: "Unique",
name: "Jane",
description: "Janes Description",
uniqueID: "22222"
}]
}
};
//Use plunk method
var uniqueIDArr = _.pluck(data.metadata.products, 'uniqueID');
console.log(uniqueIDArr);
//=> ["11111", "22222"]
//Use map function
var uniqueIDArr = _.map(data.metadata.products, function(obj) {
return obj.uniqueID;
});
console.log(uniqueIDArr);
//=> ["11111", "22222"]
<script src="https://cdn.jsdelivr.net/underscorejs/1.8.3/underscore-min.js"></script>
You can use Array.prototype.map() to create a new array and chain a Array.prototype.join() to get the uniqueIDsString in a single line:
var obj = {metadata: {products: [{type: "Unique",name: "Joe",description: "Joes Description",uniqueID: "11111"}, {type: "Unique",name: "Jane",description: "Janes Description",uniqueID: "22222"}]}},
uniqueIDsString = obj
.metadata
.products
.map(function(product) {
return product.uniqueID;
})
.join(', ');
console.log(uniqueIDsString);

How can I remap one JSON lines to hierachycal JSON?

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));

Categories