Accessing a specific key in JSON? - javascript

I'm trying to access the "title" section (key?) of this JSON object using NodeJS. I can return the entire object, but every time I try to access the key, undefined is returned.
[
[
{
"id": 119,
"title": "Roadhouse",
"url": "https://funsite.com/2021/03/20/funny/",
"date": "2021-03-20"
}
],
[
{
"id": 208,
"title": "New Sites",
"url": "https://coolsitestuff.com/notes/coolsite/",
"date": "2021-03-17"
}
],
[
{
"id": 13,
"title": "woah sites!!",
"url": "https://now.lettuce.com/then/2021-0000/",
"date": "2021-03-07"
}
],
[
{
"id": 120,
"title": "mynewalbumn",
"url": "https://notarealsite.com/2021/03/06/next-album/",
"date": "2021-03-06"
}
],
[
{
"id": 140,
"title": "fightingthemans",
"url": "http://fightcats.com/2021/03/06/keyfights",
"date": "2021-03-06"
}
],
[
{
"id": 14,
"title": "biggest lettuce youll ever see",
"url": "https://morelettuce.com/then/biggestlettuceleaf/",
"date": "2021-02-28"
}
]
]
NodeJS
const fs = require('fs')
fs.readFile('./data/links.json', 'utf8', (err, fsToString) => {
let data = JSON.parse(fsToString);
console.log(data.map(link => link[link.url]))
})
I've tried for loops and indexing that way but I haven't been able to get anything out of it.

You have 2 arrays, either loop over both of them or access it using index
let data =[
[
{
"id": 119,
"title": "Roadhouse",
"url": "https://funsite.com/2021/03/20/funny/",
"date": "2021-03-20"
}
],
[
{
"id": 208,
"title": "New Sites",
"url": "https://coolsitestuff.com/notes/coolsite/",
"date": "2021-03-17"
}
]
]
data.map(link=> console.log(link[0].url))

Your json is array of array objects, you need to access all arrays by index, you can use flatMap and map methods.
var data = [
[{
"id": 119,
"title": "Roadhouse",
"url": "https://funsite.com/2021/03/20/funny/",
"date": "2021-03-20"
}],
[{
"id": 208,
"title": "New Sites",
"url": "https://coolsitestuff.com/notes/coolsite/",
"date": "2021-03-17"
}],
[{
"id": 13,
"title": "woah sites!!",
"url": "https://now.lettuce.com/then/2021-0000/",
"date": "2021-03-07"
}],
[{
"id": 120,
"title": "mynewalbumn",
"url": "https://notarealsite.com/2021/03/06/next-album/",
"date": "2021-03-06"
}],
[{
"id": 140,
"title": "fightingthemans",
"url": "http://fightcats.com/2021/03/06/keyfights",
"date": "2021-03-06"
}],
[{
"id": 14,
"title": "biggest lettuce youll ever see",
"url": "https://morelettuce.com/then/biggestlettuceleaf/",
"date": "2021-02-28"
}]
];
console.log(data.flatMap(i=>i.map(f=>f.url)))

Your current code is trying to access an undefined object property.
Solution:
Replace the link[link.url] for link[0].url. So that the full line is
console.log(data.map(link => link[0].url))
Or if you want the titles:
console.log(data.map(link => link[0].title))

console.log(
data.flat().map(link=>link.url)
);
console.log(
data.map(item=>item[0].url)
);

From what I see your JSON file holds an array of arrays and each nested array contains one object. Therefore data.map(link => link[0].title) should return array of titles

You have an array of arrays and each one with just one position. For the code you posted you're just missing the index of each element.
If you change your code to this you'll get the array with the URL's you're looking for
fs.readFile('./example.json', 'utf8', (err, fsToString) => {
let data = JSON.parse(fsToString);
console.log(data.map(link => link[0].url))
})
Happy coding ;)!

Related

Transforming a complex object into an array

I am creating a React app using data from an API. the response data is a long complicated object that looks something like this:
{
"Frozen Products": [
{
"_id": "6181849285e8d8f86be2d9df",
"name": "Peas (800g)",
"category_id": "6181841060c425f76e57b603",
"slug": "vegetables",
"quantity": 16,
"price": {
"amount": 3.00
},
"thumbnail":"URI ...",,
"images": [
"URI ...",
],
"synonyms": [
"Veggies"
],
},
//etc for many key/values inside this object ..
}
I need to access the information do display a category ("Frozen Products" in this case) and all the product names and images under it.
But I think I need to access each Key/Value pair by loopin through their index (example data[0]) not the Key name since they keys are dynamically created by an API. So how can I change this to:
{
[ "Frozen Products": [
{
"_id": "6181849285e8d8f86be2d9df",
"name": "Peas (800g)",
"category_id": "6181841060c425f76e57b603",
"slug": "vegetables",
"quantity": 16,
"price": {
"amount": 3.00
},
"thumbnail":"URI ...",,
"images": [
"URI ...",
],
"synonyms": [
"Veggies"
],
},
]
I think you need something like this:
let data = {
"Frozen Products": [
{
"_id": "6181849285e8d8f86be2d9df",
...
}
],
"Another Category": [...]
}
let categories = Object.keys(data).map((key) => ({categoryName: key, products: data[key]}));
you can loop through an object with for in iterator.
No matter what key names are
for(key in object) {
let value = object[key];
}

JSON: How to get data from a same "column" with different names?

I have my JSON file as follows:
{
"data": {
"member1": {
"id": 1,
"name": "Gather",
"symbol": "AB1"
"last_updated": 1525137271
},
"member2": {
"id": 2,
"name": "Banner",
"symbol": "AB2",
"last_updated": 1525137260
},
"member3": {
"id": 3,
"name": "Tecker",
"symbol": "AB3",
"last_updated": 1525137260
},
"member4": {
"id": 4,
"name": "Walter",
"symbol": "AB4",
"last_updated": 1525137260
}
}
I would like to get the data ONCE from "member1", "member2"...
Of course it would be easy to get the data if the names were all identical. Any ideas ?
You can use Object.keys, Object.values and Object.entries to enumerate the properties of an object.
In your case, for example, let's say we wanted an array of all the names:
Object.values(json.data).map(member => member.name)
Here's a nice article that explains the three.

Retrieve data from nested arrays

How can I retrieve ids from a nested array?
Initially I get such json response and I need to get all ids from all nested arrays.
Anybody can help me out here?
Should I use filter or any of find functions?
An example or explanation could be great.
{
"id": 271,
"name": "anything",
"description": null,
"entries": [
{
"id": "fda2afe0-dfc4-4373-9e50-8b140a46f25e",
"name": "first occurence",
"runs": [
{
"id": 284,
"name": "the element from which I want to get id",
"description": null,
"created_on": 1530627823,
"created_by": 2
},
{
"id": 285,
"name": "element for id 2",
"created_by": 2
},
{
"id": 296,
"name": "element for id 3",
"created_on": 1530710993,
"created_by": 2
}
]
},
{
"id": "a65dd3f0-3fc1-4f93-9123-f5a05ae50703",
"name": "second occurence",
"runs": [
{
"id": 272,
"name": "element for id 4",
"created_by": 2,
},
{
"id": 273,
"created_by": 2,
},
{
"id": 274,
"created_by": 2,
}
]
}
]
}
Assuming you're looking for the deepest IDs (Run IDs), here is an example of how it can be done.
let response = {"id":271,"name":"anything","description":null,"entries":[{"id":"fda2afe0-dfc4-4373-9e50-8b140a46f25e","name":"first occurence","runs":[{"id":284,"name":"the element from which I want to get id","description":null,"created_on":1530627823,"created_by":2},{"id":285,"name":"element for id 2","created_by":2},{"id":296,"name":"element for id 3","created_on":1530710993,"created_by":2}]},{"id":"a65dd3f0-3fc1-4f93-9123-f5a05ae50703","name":"second occurence","runs":[{"id":272,"name":"element for id 4","created_by":2,},{"id":273,"created_by":2,},{"id":274,"created_by":2,}]}]}
function getRunIDs() {
let entries = response['entries'] || []
let runIDs = []
entries.forEach(entry => {
entry['runs'].forEach(run => {
runIDs.push(run['id'])
})
})
return runIDs
}
console.log({ runIDs: getRunIDs() })
Assuming you store that json in some variable, say json,
const ids = json.entries.map(entry => entry.runs.map(run => run.id));
should give you a nested array of the IDs that looks like
[ [ 284, 285, 296 ], [ 272, 273, 274 ] ].
If you wanted this to be in a single dimension list, i.e.
[ 284, 285, 296, 272, 273, 274 ],
you can use concat.apply.
const concatIds = [].concat.apply([], ids);
Filter and find functions would be redundant because you are obtaining all the ids and not specific ones. To solve your problem you can simply just use functions with map . For this example, your object will be called exampleObj in which you can simply do this to get the array of all ids:
exampleObj.entries.map(entryObj => {
return entryObj.runs.map(runObj=>{return runObj.id});
});

Using lodash, how I can get the maximum length of nested array object

I need to take the data from below mentioned array of object which has maximum length of nested array object. As per below my request, id : 2 values has 3 objects, result will be as mentioned below.
Anyone help me using lodash or some javascript function to achieve this.
Sample Request:
[{
"id": 1,
"values": [
{
"sub": "fr",
"name": "foobar1"
},
{
"sub": "en",
"name": "foobar2"
}
]
},
{
"id": 2,
"values": [
{
"sub": "fr",
"name": "foobar3"
},
{
"sub": "en",
"name": "foobar4"
},
{
"sub": "ts",
"name": "foobar5"
},
]
}]
Expected output:
"values": [
{
"sub": "fr",
"name": "foobar3"
},
{
"sub": "en",
"name": "foobar4"
},
{
"sub": "ts",
"name": "foobar5"
},
]
}]
This can be achieved using the native javascript reduce function as follows
var source = [...];
source.reduce((max, cur) => cur.values.length > max.values.length ? cur : max, source[0])

jQuery UI Autocomplete - accessing nested objects in JSON

I'm trying to use the jQuery UI Autocomplete widget with a custom JSON feed I'm getting back from an API, which is formatted as follows:
{
"SearchTerm": "ches",
"HasDirectCountyHit": false,
"DirectCountyHitId": null,
"HasDirectLocationHit": false,
"DirectLocationHitId": null,
"Developments": [
{
"Id": "45339ae3e55a",
"Label": "Chestnut Walk, Bilston",
"Url": "/developments/chestnut-walk-bilston"
},
{
"Id": "4835f52e053a",
"Label": "Crown Park, Chester",
"Url": "/developments/crown-park-chester"
},
{
"Id": "757964964cc6",
"Label": "The Birches, West Timperley",
"Url": "/developments/the-birches-west-timperley"
}
],
"Counties": [
{
"Id": "7",
"Label": "Cheshire",
"Url": "/search?cid=7"
},
{
"Id": "24",
"Label": "Greater Manchester",
"Url": "/search?cid=24"
}
],
"Locations": [
{
"Id": "12061",
"Label": "Cheselbourne, Dorset (DT2 7)",
"Url": "/search?lid=12061"
},
{
"Id": "12062",
"Label": "Chesham, Buckinghamshire (HP5 1)",
"Url": "/search?lid=12062"
},
{
"Id": "12063",
"Label": "Chesham, Greater Manchester (BL9 6)",
"Url": "/search?lid=12063"
},
{
"Id": "12064",
"Label": "Chesham Bois, Buckinghamshire (HP6 5)",
"Url": "/search?lid=12064"
},
{
"Id": "12065",
"Label": "Cheshunt, Hertfordshire (EN8 9)",
"Url": "/search?lid=12065"
},
{
"Id": "12066",
"Label": "Chesley, Kent (ME9 7)",
"Url": "/search?lid=12066"
},
{
"Id": "12067",
"Label": "Cheslyn Hay, Staffordshire (WS6 7)",
"Url": "/search?lid=12067"
},
{
"Id": "12068",
"Label": "Chessetts Wood, Warwickshire (B94 6)",
"Url": "/search?lid=12068"
},
{
"Id": "12069",
"Label": "Chessington, Kingston upon Thames - Greater London (KT9 2)",
"Url": "/search?lid=12069"
},
{
"Id": "12070",
"Label": "Chessmount, Buckinghamshire (HP5 1)",
"Url": "/search?lid=12070"
}
]
}
The API I'm calling returns results based on my search term, so I know that all of the results in the nested objects are matches - my problem is how to access these objects ('Developments', 'Counties' and 'Locations') so that the autocomplete widget can pick up the 'Label' values?
Thanks,
Robin
Ok - here's what you can do:
//put all the keys you want to pull out of your json in an array
var props = [
"Locations", "Counties", "Developments"
];
//empty array for your autocomplete
var labels = [];
//loop thru all the properties you care about
$.each(props, function () {
$.each(source[this], function () {
//and pull out all the labels and add them to the labels array
labels.push(this.Label)
});
});
$("#autocomplete").autocomplete({
source: labels
});
and to see it all in action I created a quick fiddle
http://jsfiddle.net/fr5yb3n0/

Categories