This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 6 years ago.
I am working on an ionic 1 app, I do not know if there is a way but for example, here, is there a way I can dynamically assign a parent in this object depending on the value of the Variable?
var contact = {
"Name": "John Doe",
"available": true,
Variable: [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]
};
Lets say Variable = "friends" Then
var contact = {
"Name": "John Doe",
"available": true,
"Friends": [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]
};
I know I can use ES6, the Computed Property Names [Variable] but they are not working on older devices. Is there any alternative method?
Just plain old
var contact = {
"Name": "John Doe",
"available": true,
};
contact[Variable] = [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]
Related
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 2 years ago.
I have this json data below:
[{
"name": "Dad",
"age": "32"
}, {
"name": "Mom",
"age": "30"
}, {
"name": "Son",
"age": "3"
}]
I would like to have an array: ["Dad", "Mom", "Son"].
What is the correct way to implement this in Javascript?
This is one way:
var result= [{
"name": "Dad",
"age": "32"
}, {
"name": "Mom",
"age": "30"
}, {
"name": "Son",
"age": "3"
}].map( item => { return item.name }); //["Dad", "Mom", "Son"]
console.log(result);
var result= [{
"name": "Dad",
"age": "32"
}, {
"name": "Mom",
"age": "30"
}, {
"name": "Son",
"age": "3"
}].map( function(item) { return item.name }); //["Dad", "Mom", "Son"]
console.log(result);
This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed 2 years ago.
I need to select multiple array elements that have the same value.
Using array.find () returns only the first element that satisfies the query condition.
The construction below shows only "Donald Trump" in console:
const data = [
{
"position": "president",
"name": "Donald Trump",
"language": "english"
},
{
"position": "president",
"name": "Vladimir Putin",
"language": "russian"
},
{
"position": "king",
"name": "Shutruk-Nahhunte",
"language": "elamite"
},
];
let result = data.find(elem => elem.position == "president");
console.log(result.name);
But I need to get all the values as an array, - something like this:
[
"Donald Trump",
"Vladimir Putin"
]
How to do it right, considering also that the real array is huge.
Thanks for any help!
I use filter to do this task
const data = [
{
"position": "president",
"name": "Donald Trump",
"language": "english"
},
{
"position": "president",
"name": "Vladimir Putin",
"language": "russian"
},
{
"position": "king",
"name": "Shutruk-Nahhunte",
"language": "elamite"
},
];
const newArray= data.filter(x=>x.position==='president')
let nameArray=newArray.map(x=>x.name)
console.log(nameArray)
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 3 years ago.
Suppose I have a JSON Object like this:
var data = {
"name": "abcd",
"age": 21,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [
{
"type": "home",
"number": "111 111-1111"
},
{
"type": "fax",
"number": "222 222-2222"
}
]
}
and I want to get the information from this json object by using path which is a string, like
var age = 'data/age'; // this path should return age
var cityPath = 'data/address/city'; // this path should return city
var faxNumber = 'data/phoneNumber/1/number'; // this path should return fax number
Is there any way I can get this information from the string path? Currently I am splitting the path by / and then using it like data.age or data.address.city. But this approach is not useful for any array contained in JSON object.
Is there any better and optimal approach in JavaScript for this problem?
This is how you can access the data from the JSON, no need to use paths:
var data = {
"name": "abcd",
"age": 21,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [
{
"type": "home",
"number": "111 111-1111"
},
{
"type": "fax",
"number": "222 222-2222"
}
]
}
var age = data.age;
var cityPath = data.address.city;
var faxNumber = data.phoneNumber[0].number; // array first item begins with 0
console.log({age, cityPath, faxNumber})
If you really need to use paths for some reason, I suggest using lodash get method https://lodash.com/docs#get
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
Having a thorny problem and only see similar but also simpler solutions on SO.
Is is possible to generate a dynamic key AND dynamic values using JS/JSON?
For instance, let's say I have JSON like this:
{
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
I need to go into the fields and for each field (products, wines, fruits) see if a given service is contained within so that I can go back and generate a product or wine or fruit for each service that requires it. But I don't want to repeat the services names more than once. The resulting JSON should look something like this:
{"svc1":["Products"], "svc2":["Products"], "svc3":["Products"], "svc4":["Fruits", "Wines"]}
The hope would be that to generate a dynamic list in Angular I can just turn and loop back through this JSON, pulling out the values for each product, fruit, wine, whatever.
I've been trying a lot of nested for loops and the like but whenever I get more than one layer down the dynamism seems to stop. I'm guessing that for this to work I need to move between JS Objects and JSON?
Right now I'm trying something like this, which isn't quite working, stringify or no. And maybe I'm flip-flopping too much between JSON and JS Objects:
var outObj = [];
var fieldItems;
$.each(jsonObj.custom.fields, function(key, item) {
fieldItems = item;
fieldItems.name = item.name;
$.each(fieldItems.services, function(key, item) {
var serviceName = item;
//check to see if the serviceName already exists
if (outObj.indexOf(serviceName) > -1) {
outObj.serviceName.push(fieldItems.name);
} else {
outObj.push(serviceName);
}
});
});
JSON.stringify(outObj);
console.log("outObj " + outObj);
I get "can't read property 'push' of undefined" errors and the like. Seems this should be possible from a single nested loop, but maybe I need to just do two passes? Any other suggestions?
To me it sounds like overcomplicated solution. You can use basic array methods of javascript to filter out required structure. I am not sure what profiling_value in the presented snippet, so I started from the object structure in OP
var desiredResult = jsonObj.custom.services.reduce(function(result, service){
result[service.name] = jsonObj.custom.fields.filter(function(field){
return field.services.indexOf(service.name) >= 0;
}).map(function(field){ return field.name; });
return result;
}, {});
This gives the expected result for mentioned object.
reduce is required to iterate over all services and accumulate result in one object. Then for each service fields are iterated to filter out only those that contain link to this service. And finally list of filtered fields is transformed (map) into list of strings - their names - and inserted into accumulator