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.
Related
This question already has answers here:
Safely turning a JSON string into an object
(28 answers)
Adding a new array element to a JSON object
(6 answers)
Closed last month.
I have the following variable holding a json array.
let requestJson = '{ "data": [ { "type": "Type1", "value": "MyValue" } ] }';
I would like to add a property called "Id" to the above object inside data array. I expect to get something like;
{ "data": [ { "type": "Type1", "value": "MyValue", "id": "123" } ] }
How can I achieve this? I tried the following:
requestJson["data"][0]["id"] = '123';
But when I print requestJson["data"] I'm getting undefined. Would appreciate any help in appending the "Id" attribute to the object inside the array above. Thanks in advance.
You need to parse your string to convert it to an Object and after that you can manipulate the data attribute
let requestJson = '{ "data": [ { "type": "Type1", "value": "MyValue" } ] }';
const parsedObject = JSON.parse(requestJson)
parsedObject.data[0].id = 1
console.log(parsedObject)
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];
}
This question already has answers here:
Remove property for all objects in array
(18 answers)
How to get a subset of a javascript object's properties
(36 answers)
How to map more than one property from an array of objects [duplicate]
(7 answers)
Closed 2 years ago.
I am trying to figure out if I can send only relevant javascript info to the frontend from the backend because I want to hide things like ID, and others when my frontend makes a request.
To put things in perspective, here is a dummy code.
[
{
"_id": "215874514845452155",
"greeting":"Hello there"
},
{
"_id": "181474545841541515",
"greeting": "General Kenobi"
},
]
when requesting, I want to get result like:
[
{
"greeting": "Hello there"
},
{
"greeting": "General Kenobi"
},
]
I am still learning stuff and I know about loop function but I want to know if there is some neat trick to it. I am coming from R programming, we hate loops.
Use Array.prototype.map:
const input = [
{
"_id": "215874514845452155",
"greeting":"Hello there",
"other":"foo"
},
{
"_id": "181474545841541515",
"greeting": "General Kenobi",
"other":"bar"
},
];
const result = input.map(({greeting,other}) => ({greeting,other}));
console.log(result);
The above is a shorthand way of writing this:
const input = [
{
"_id": "215874514845452155",
"greeting":"Hello there",
"other":"foo"
},
{
"_id": "181474545841541515",
"greeting": "General Kenobi",
"other":"bar"
},
];
const result = input.map(x => {
return {
greeting: x.greeting,
other: x.other
}
});
console.log(result);
This question already has answers here:
Parsing "relaxed" JSON without eval
(6 answers)
Safely parsing a JSON string with unquoted keys
(5 answers)
Closed 2 years ago.
Legs: [{
'dollar': {
xmlns: 'HitchHiker.FlightAPI.FareRequestStructs'
},
FareRequestLeg: [{
ArrivalSearchRadius: ['0'],
ArrivalTime: [{
'dollar': {
'xsi:nil': 'true'
}
}],
Class: ['Economy'],
Connections: [''],
DepartureDate: ['2020-10-22T00:00:00'],
DepartureSearchRadius: ['0'],
DepartureTime: [{
'dollar': {
'xsi:nil': 'true'
}
}],
}]
}]
I have some thing like that.
I had a xml file. I use Xml2js for parsing , here i got a this string
I want Object from of this.
clear view : https://pastebin.com/ZvPAbdgw
Use something like https://jsonlint.com/ to check your json format,
I fixed few lines for you
{
"Legs": [{
"dollar": {
"xmlns": "HitchHiker.FlightAPI.FareRequestStructs"
}
}]
}
then you could assign it to a variable.
const json = {
"Legs": [{
"dollar": {
"xmlns": "HitchHiker.FlightAPI.FareRequestStructs"
}
}]
}
If the format returned is string you would need to do
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
const jsonObj = JSON.parse("your json string")
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.