trying to reference a field in this JSON but it's unlike anything in the examples I've been looking at so I'm kinda stumped.
I want to know how to reference the field at the end "HOW DO I REFERENCE THIS?". Thanks for any help.
var JSON =
{ "employees": {
"name" : "david",
"car" : "audi"
},
{
"name" : "jimmy",
"car" : "VW"
},
"customers" : {
"name" : "philip",
"purchase": "cabbage"
},
{
"name" : "Helen",
"purchase": "HOW DO I REFERENCE THIS?"
}
}
var x = "HOW DO I REFERENCE THIS?";
With the right syntax, which I believe you want this:
var JSON = {
"employees": [
{
"name": "david",
"car": "audi"
},
{
"name": "jimmy",
"car": "VW"
}],
"customers": [
{
"name": "philip",
"purchase": "cabbage"
},
{
"name": "Helen",
"purchase": "HOW DO I REFERENCE THIS?"
}]
}
You can get purchase by using this:
for (var i in JSON.customers)
{
var customer = JSON.customers[i];
var value = customer.purchase; // cabbage, HOW DO I...
}
try this:
var JSON = {
"employees": [{
"name": "david",
"car": "audi"
}, {
"name": "jimmy",
"car": "VW"
}],
"customers": [{
"name": "philip",
"purchase": "cabbage"
}, {
"name": "Helen",
"purchase": "HOW DO I REFERENCE THIS?"
}]
}
$.each(JSON.customers, function (k, data) {
alert(data.purchase);
});
Working Fiddle
Do you need to find the purchase string for "Helen" or just the second customer, if it's the second customer it will be (with valid JSON):
var string = '{"employees": [{"name": "david", "car": "audi"}, {"name": "jimmy", "car": "VW"}], "customers": [{"name": "philip", "purchase": "cabbage"}, {"name": "Helen", "purchase": "HOW DO I REFERENCE THIS?"}]}';
var string = JSON.parse(string);
console.log(string['customers'][1]['purchase']);
and if you need to find "Helen" it would be something like this (with valid JSON):
var string = '{"employees": [{"name": "david", "car": "audi"}, {"name": "jimmy", "car": "VW"}], "customers": [{"name": "philip", "purchase": "cabbage"}, {"name": "Helen", "purchase": "HOW DO I REFERENCE THIS?"}]}';
var string = JSON.parse(string);
for (var i=0 ; i < string['customers'].length ; i++) {
if (string['customers'][i]["name"] == "Helen") {
var result = string['customers'][i]['purchase'];
}
}
console.log(result);
Related
I have problem with get string in JSON data. Format as below:
[
{
"name": "Alice",
"age": "20"
},
{
"id": "David",
"last": "25"
},
{
"id": "John",
"last": "30"
}
]
Sometime it changes position together, John from 3rd place go to 2nd place:
[
{
"name": "Alice",
"age": "20"
},
{
"name": "John",
"age": "30"
},
{
"name": "David",
"age": "25"
}
]
If i use data[3].age to get John's age, and data change position, I will get David's age.
Is there any method I can use to find the object with name David and get the age value?
You can use array.find() method as,
var myArray = [
{
"name": "Alice",
"age": "20"
},
{
"name": "John",
"age": "30"
},
{
"name": "David",
"age": "25"
}
];
//Here you are passing the parameter name and getting the age
//Find will get you the first matching object
var result = myArray.find(t=>t.name ==='John').age;
console.log(result);
It's better to use array.filter() (better browser support)
myArray.filter(function(el){return el.name == "John"})[0].age
I have a large array of users which are comprised of 3 different user types ("Admin", "Moderator", "User"). Each user will have the following properties: ("name", "companyId", "type").
The first method will take 1 parameter: an array of users and must return a grouped list according to the user property "type".
The second method will take 4 parameters: a grouped list (result from the first method), an array of user types to include in the search, a string representing the user property to filter by and a string representing the value of the user property. This method must return an array of users as per the search parameters.
My method constructions are returning weird results. Could someone help?
let userTypes = ["Admin", "Moderator", "User"]
function orchestrateUsers(users) {
let result = [];
users.forEach(user => {
result.push({
"name": user.name,
"type": user.type
});
});
return result;
}
function searchUsers(orchestratedUsers, userTypes, property, value) {
}
const users= [{
"name": "Joe",
"companyId": "A2100",
"type": "Admin"
},
{
"name": "Jane",
"companyId": "A2100",
"type": "Moderator"
},
{
"name": "Smith",
"companyId": "A2100",
"type": "User"
},
{
"name": "Smith",
"companyId": "A2100",
"type": "User"
},
{
"name": "Rocket",
"companyId": "A3100",
"type": "Admin"
},
{
"name": "Rick",
"companyId": "A3100",
"type": "User"
},
{
"name": "Tim",
"companyId": "A4100",
"type": "Admin"
}
]
console.log(orchestrateUsers(users));
Answering the first question
const users = [{ "name": "Joe", "companyId": "A2100", "type": "Admin" }, { "name": "Jane", "companyId": "A2100", "type": "Moderator" }, { "name": "Smith", "companyId": "A2100", "type": "User" }, { "name": "Smith", "companyId": "A2100", "type": "User" }, { "name": "Rocket", "companyId": "A3100", "type": "Admin" }, { "name": "Rick", "companyId": "A3100", "type": "User" }, { "name": "Tim", "companyId": "A4100", "type": "Admin" } ]
function orchestrateUsers(users) {
let result = {};
users.forEach(user => {
if (result[user.type]) result[user.type].push(user.name);
else result[user.type] = [user.name];
});
return result;
}
console.log(orchestrateUsers(users));
It looks like you want something like lodash. Here's an example using _.groupBy to group users by type & _.filter to filter for admins:
const users = [
{"name": "Joe", "companyId": "A2100", "type": "Admin"},
{"name": "Jane", "companyId": "A2100", "type": "Moderator"},
{"name": "Smith", "companyId": "A2100", "type": "User"},
{"name": "Rick", "companyId": "A3100", "type": "User" }
];
var usersByType = _.groupBy(users, function (user) {
return user.type;
});
console.log(usersByType);
var admins = _.filter(users, function(user) {
return user.type === "Admin";
});
console.log(admins);
console.log(Object.keys(usersByType));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
Run the code snippet to see the console output.
Why Lodash?
Lodash makes JavaScript easier by taking the hassle out of working
with arrays, numbers, objects, strings, etc. Lodash’s modular methods
are great for:
Iterating arrays, objects, & strings
Manipulating & testing values
Creating composite functions
I have an array of objects of the structure coming from server response of iterated array object like as sample
array[1] ={
"ID": "123",
"Name": "John",
"Age": "15"
}
array[2] ={
"ID": "456",
"Name": "Sue",
"Age": "18"
}
array[n] ={
}
But now I want to append the array values if the condition age below 18 in the following structure of as iterated values of above array
Expected Output:
{
"Stud": [{
"ID": "123",
"Name": "John",
"Age": "15"
}, {
"ID": "456",
"Name": "Sue",
"Age": "18"
},{n........
}]
}
var output = { "Stud" : [] };
for (var i = array.length - 1; i >= 0; i--) {
if (array[i].Age < 18) {
output.Stud.push(array[i]);
}
}
console.log(output);
Simply
var output = { "Stud" : array }; //existing 'array'
You can use array#filter to select objects with age less than or equal to 18.
const response = [{
"ID": "123",
"Name": "John",
"Age": "15"
},{
"ID": "456",
"Name": "Sue",
"Age": "18"
},{
"ID": "459",
"Name": "Jaby",
"Age": "20"
}];
const result = response.filter(o => o.Age <= 18);
var output = {'stud' : result};
console.log(output);
Simply iterate and check whether the age is < 18 or not. If so push that to another array.
var array = [];
var array_below_18 = [];
array[0] ={
"ID": "123",
"Name": "John",
"Age": "15"
}
array[1] ={
"ID": "456",
"Name": "Sue",
"Age": "18"
}
array[1] ={
"ID": "456",
"Name": "Sue",
"Age": "14"
}
for(i=0;i<array.length;++i){
if(parseInt(array[i].Age)<18){
array_below_18.push(array[i]);
}
}
var final_object = {
"Stud" : array_below_18
}
console.log(final_object);
I need help regarding rendering this JSON data in html table using angular:
[{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 50,
"name": "John"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}]
My rendered html table should look like this
Test1 Test2
John 20 50
Doug 10 100
Somehow values need to be grouped by, and then rendered, but to keep matching data. Also that first position in array[0][0] should be empty. Any help will be appreciated.
So you can group your data by name , and have Object of arrays like following :
{
"John": [
{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test2",
"number": 50,
"name": "John"
}
],
"Doug": [
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}
]
}
Then , define a function to retrieve data by name & task : getItemBy=function(name,task)
Those two steps will make your algo easy to render HTML table as u want :
DEMO :
var data=[{
"task": "Test1",
"number": 20,
"name": "John"
},
{
"task": "Test1",
"number": 10,
"name": "Doug"
},
{
"task": "Test2",
"number": 50,
"name": "John"
},
{
"task": "Test2",
"number": 100,
"name": "Doug"
}];
var groupBy=function(arr,key) {
return arr.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
//------
var groupedByName=groupBy(data,'name');
var getItemBy=function(name,task){
return groupedByName[name].filter((item)=>item.task===task)
};
//------
//--
console.log(`***** Item where name=John & task=Test1`,
getItemBy('John','Test1')
)
console.log(`****** All data after grouping`,
groupedByName
)
This question already has answers here:
Sorting Object by sub-object property
(4 answers)
Closed 7 years ago.
How to sort the objects by age value?
I have the following object structure
{
"men": {
"20114": {
"id": "20114",
"name": "Peter",
"age": "21"
},
"28957": {
"id": "28957",
"name": "Paul",
"age": "20"
}
},
"women": {
"8957": {
"id": "8957",
"name": "Rose",
"age": "24"
},
"2178": {
"id": "2178",
"name": "Sara",
"age": "22"
}
},
}
I know, that I can sort arrays like this
groups.sort(function(a, b) {
return b.age - a.age;
});
but how to do this with objects?
It would be a lot easier to sort your data if you could change your structure to the JSON model below:
var data = [
{
"id": "20114",
"name": "Peter",
"age": "21",
"gender": "men"
},
{
"id": "28957",
"name": "Paul",
"age": "20",
"gender": "men"
},
{
"id": "8957",
"name": "Rose",
"age": "24",
"gender": "women"
},
{
"id": "2178",
"name": "Sara",
"age": "22",
"gender": "women"
}
]
data.sort(function(a, b) {
return parseFloat(a.age) - parseFloat(b.age);
});
data.sort()
document.write(JSON.stringify(data))
function sortfunc(prop){
return function(obj1,obj2){
var val1 = obj1[prop];
var val2 = obj2[prop];
return val1 - val2;
};
}
groups.sort(sortfunc(prop));
pass prop as property name