Javascript Object traversal with String [duplicate] - javascript

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 8 years ago.
I need to traverse a JavaScript object with a stored string.
Sample string
var x = "Desserts"
Sample Object
{
"dataset":
{
"Categories" :
[
{
"Desserts" :
[
"Sweets","Ice Creams","Pastry"
]
} ,
{
"Juices and Beverages" :
[
"Cold","Hot","Fresh","Sodas"
]
}
}
}
If I traverse the object as dataset.Categories.x, it doesn't work[returns undefined] . How can I do this?

You should use dataset.Categories[0][x] instead of dataset.Categories[0].x
Take a look at : dot notation or the bracket notation
var x = "Desserts",
data = {
"dataset": {
"Categories": [{
"Desserts": ["Sweets", "Ice Creams", "Pastry"]
}, {
"Juices and Beverages": ["Cold", "Hot", "Fresh", "Sodas"]
}]
}
}
alert(data.dataset.Categories[0][x]);

var obj = {
"dataset": {
"Categories": [{
"Desserts": ["Sweets", "Ice Creams", "Pastry"]
}, {
"Juices and Beverages": ["Cold", "Hot", "Fresh", "Sodas"]
}]
}
}
var x = 'Desserts';
var val = obj.dataset.Categories[0][x];
console.log(val);
JSFIDDLE.

Related

Javascript proper way to .push array [duplicate]

This question already has an answer here:
javascript push returning number instead of object [duplicate]
(1 answer)
Closed 3 months ago.
How to use .push array in proper way using javascript?
my code
let persons = [{
"person1": "person1"
},
{
"person1": "person1"
}
]
let addPerson = []
addPersn.push({
"person1": "person2"
})
let allPerson = persons.push(addPerson)
console.log(allPerson)
expected behavior
{
"person1": "person1"
},
{
"person1": "person1"
},
{
"person1": "person1"
}
current result
3
How to use .push array in proper way using javascript?How to use .push array in proper way using javascript?
Try this
let persons = [
{
person1: "person1",
},
{
person2: "person2",
},
];
const newPerson = {
person3: "person3",
}
persons.push(newPerson);
console.log(persons);

How to create filter by object name in typescript [duplicate]

This question already has answers here:
Using bracket notation opposed to eval
(1 answer)
Convert a string to a variable name in javascript?
(3 answers)
Closed 1 year ago.
I have data like this
{
"data": {
"x": [
{
"id": 1,
"y": "yData1"
},
{
"id": 2,
"y": "yData2"
}
],
"xx": {
"xxx": [
{
"id": 1,
"yyy": "yyyData1"
},
{
"id": 2,
"yyy": "yyyData2"
}
]
}
}
}
sometime i just want object x or xx or xxx or many sub children in datas, i ready using eval for filter by using object name to return data
filter(data: any, key: any) {
return eval("data." + key)
}
any idea ?? because eval in typescript/javascript not recommended
Just use bracket notation in order to use variable values as key:
filter(data: any, key: any) {
return data[key];
}

Remove empty Object from JSON arrays [duplicate]

This question already has answers here:
Remove Object From Array if the value is empty in name and value pair js
(3 answers)
Closed 2 years ago.
I am trying to remove this empty key value pair object from this JSON array but it I am unable to figure out on how to do it.
I tried this:
var array = {
"title":[
{"lang":"English","value":"yes"},
{"lang":"Spanish","value":"no"},
{"lang":"German","value":""}
]
}
var result = array['title'].filter(function(x){return x.length});
This gives the following output:
{
"title":[
{"lang":"English","value":"yes"},
{"lang":"Spanish","value":"no"},
{"lang":"German"}
]
}
Output expected:
{
"title":[
{"lang":"English","value":"yes"},
{"lang":"Spanish","value":"no"}
]
}
Change your filter to look for an empty string in the value property:
var array = {
"title": [{
"lang": "English",
"value": "yes"
},
{
"lang": "Spanish",
"value": "no"
}, {
"lang": "German",
"value": ""
}
]
}
var result = array['title'].filter(x=>x.value !== "");
console.log(result);
You should do something like this.
array['title'].filter( element => element.value )
You aren't specifying what it's looking for for each element.
Try changing your filter function to check if the value exists and has a length greater than 0:
function(x) { return x.value && x.value.length > 0 }

Create JSON object starting from another JSON Object for Materialize Autocomplete [duplicate]

This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Closed 2 years ago.
I'm trying to work with autocomplete from Materialize.
The API Request provides following data:
[
{
"id": 4007,
"name": "Curitiba, Paraná, BR"
},
{
"id": 4391,
"name": "Curitibanos, Santa Catarina, BR"
}
]
But I need format this data using JavaScript in something that looks like:
{
"Curitiba, Paraná, BR": null,
"Curitibanos, Santa Catarina, BR" , null
}
Thank you in advance for any help! :)
You can map your array of objects to an array of {[name]: null} objects. Here [name] is a computed property name, which allows you to use the value of the name variable as the key for your object. You can then merge the mapped array into one resulting object using Object.assign() along with the spread syntax (...).
See example below:
const arr= [ { "id": 4007, "name": "Curitiba, Paraná, BR" }, { "id": 4391, "name": "Curitibanos, Santa Catarina, BR" } ];
const res = Object.assign(...arr.map(({name}) => ({[name]: null})));
console.log(res);
All you have to do for this is to assign each name as a key in a new object:
const data = [
{
"id": 4007,
"name": "Curitiba, Paraná, BR"
},
{
"id": 4391,
"name": "Curitibanos, Santa Catarina, BR"
}
];
var object = {};
var i = 0;
for (i = 0; i < data.length; i++) {
object[data[i].name] = null;
};
console.log(object);

get value from json when passed key is a variable [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I am creating a list by fetching values from a JSON file. It is a nested JSON and the list items are- "Thriller","Fiction" which are basically keys for the next level.
on click of the item I'm passing its name(i.e. Thriller/fiction) to another function...
var val = thriller.
Now I need to fetch the value(i.e. "book" & bookname) corresponding to the passed key in this new function. I'm not able to do so using dot operator-
data.library.val not working..
If anybody has worked on something similar..please help..
JSON:
{ "library": [
{
"Thriller": [
{ "book": "ABC" },
{ "book": "DEF" }
]
},
{
"Fiction": [
{ "book": "GHI" },
{ "book": "JKL" }
]
},] }
Code snippet:
$.getJSON('resources/abc.json', function(data){
var i = data.library;
$("#menuList1").css('display','block');
$(i).each(function(key, value){
$.each(value, function(key, value){
console.log(key);
$("#menuList1").append(''+key+'');
});
}); });
Use data.library[key]
MDN Documentation
Your Json is not valid, this },] specially. A good version :
{
"library": [{
"Thriller": [{
"book": "ABC"
}, {
"book": "DEF"
}]
}, {
"Fiction": [{
"book": "GHI"
}, {
"book": "JKL"
}]
}]
}
you can refer the website http://jsonlint.com for validating your json.

Categories