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});
});
Related
I want to be able to parse this json tree and get the value of the attribute checked for every element :
{
"children": [
{
"children": [
{
"children": [],
"id": 49,
"name": "nice",
"checked": true,
"level": 3,
"path": "0_1_0_0",
"lineLength": 180
}
],
"id": 48,
"name": "amira",
"checked": false,
"level": 2,
"path": "0_1_0"
}
],
"id": 47,
"name": "mahdi",
"checked": true,
"level": 1,
"path": "0_1"
}
I'm able to read the data this way :
var data = this.flatData;
I want to be able to read the checked attribute for every child inside a for loop or a foreach and if it's true set a certain behaviour to my code do any one know how to do this and thanks in advance.
You can use a recursion; in your particular structure something like:
const func = (elem) => {
if (elem.children) elem.children.forEach((elem) => func(elem));
if (elem.checked) console.log(`act on elem with id: ${elem.id}`);
}
func(test);
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 ;)!
For each object inside this array containing userHandle array loop through that array(userHandle one) and check if one of those values matches some string I choose called uid. How to write that code in Javascript?
Array [
Object {
"avatar": null,
"hugCount": 2,
"id": 35,
"liked": false,
"name": "fhfdhdhf",
"text": "Yoho",
"timestamp": 1610471860157,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
},
Object {
"avatar": null,
"hugCount": 1,
"id": 34,
"liked": true,
"mood": 2,
"name": "fhfdhdhf",
"text": "I'm fine today.",
"timestamp": 1607943705709,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
"userHandle": Array [
"Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
"LrIwIx9I1xQBJ7aeCSrinpEaDP53",
],
}]
Try this code:
var uid = "LrIwIx9I1xQBJ7aeCSrinpEaDP53";
yourArray.forEach(function(item, _){
return item['userHandle']?.indexOf(uid);
});
The '?' is to make sure your Object contains the 'userHandle' property
This is the function you need... and below you can see how to use it.
You need to pass the value you are looking for, and the array with the information.
function findInUserHandle(uidValue, array)
{
return array.reduce
(
(acum, current) =>
current.userHandle && current.userHandle.indexOf(uidValue) !== -1 || acum,
false
)
}
let array = [
{
"avatar": null,
"hugCount": 2,
"id": 35,
"liked": false,
"name": "fhfdhdhf",
"text": "Yoho",
"timestamp": 1610471860157,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
},
{
"avatar": null,
"hugCount": 1,
"id": 34,
"liked": true,
"mood": 2,
"name": "fhfdhdhf",
"text": "I'm fine today.",
"timestamp": 1607943705709,
"uid": "FOgepuJqxXfkHxI8OAV2KMWodXo1",
"userHandle":[
"Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
"LrIwIx9I1xQBJ7aeCSrinpEaDP53",
],
}
]
findInUserHandle('something', array) //? false
findInUserHandle('Aw8AUj1mPkON1Fd1s6LhkNETHfb2', array) //? true
findInUserHandle('mood', array) //? false
following up on my previous question about transforming data using lodash, this time i require output to be an object properties instead of being a collection. I appreciate the help and if someone can also guide me where to begin properly so i have a better understanding of these concepts
Sample Data
{
"changeAccount": {
"add": [
{
"changeType": 1,
"type": "changeAccount",
"updated": {
"id": 71,
"company": 124201,
"user": 8622
}
}
],
"remove": [
{
"changeType": 2,
"type": "changeAccount",
"updated": {
"id": 70,
"company": 124201,
"user": 8622
}
}
]
},
"changeproduct": {
"add": [
{
"changeType": 1,
"type": "changeproduct",
"updated": {
"id": 15,
"company": 124201,
"user": 8622
}
}
],
"remove": []
}
}
Expected Result
var sample = [{
"changeType": 1,
"type": "changeAccount",
"updated": {
"id": 71,
"company": 124201,
"user": 8622
}
},
{
"changeType": 2,
"type": "changeAccount",
"updated": {
"id": 70,
"company": 124201,
"user": 8622
}
},
{
"changeType": 1,
"type": "changeproduct",
"updated": {
"id": 15,
"company": 124201,
"user": 8622
}
}
]
Here is one way to do it:
chain(data)
.values()
.map(_.values)
.flatMapDeep()
.value()
So what's happening here is:
Start with our data which is an object
Use .values to return only the values of our top level properties (i.e. strip away changeProduct and changeAccount
Map the resulting items in the array to only the values of our objects (i.e. strip away add and remove) using .values again
Flatten the entire array recursively so we end up with an array that is one level deep using .flatMapDeep
You might also notice the chain(data) syntax, this is just a way to improve the readability and sometimes performance of your lodash code, so that you don't have to nest each lodash function that you use. Check out the docs on chain for more info.
I'm trying to accessing a json child object which is not in an array. i've tried accessing it with my below script but its not working. i want to be able to access the menuCategory Object
JSON
[
{
"id": 67,
"name": "Wednesday Menu",
"serveDate": "2019-06-12 00:00:00",
"expiryDate": "2019-06-12 16:11:00",
"status": "APPROVED",
"isEnabled": true,
"meals": [
{
"id": 45,
"name": "Waakye, Gari and Wele",
"description": "A very well designed food for all kids",
"image": "",
"mealType": "LUNCH",
"unitPrice": 30,
"status": "ENABLED"
},
{
"id": 46,
"name": "Gari and Beans",
"description": "A very well designed food for all kidsss",
"image": "",
"mealType": "LUNCH",
"unitPrice": 12,
"status": "ENABLED"
}
],
"menuCategory": {
"id": 2,
"name": "hello"
}
}
]
JAVASCRIPT
callEditMenu(parent, content) {
this.modalService.open(content);
this.editMenuCategoryId = parent.menuCategory.id;
}
May be like
const parent = [{"id":67,"name":"Wednesday Menu","serveDate":"2019-06-12 00:00:00","expiryDate":"2019-06-12 16:11:00","status":"APPROVED","isEnabled":true,"meals":[{"id":45,"name":"Waakye, Gari and Wele","description":"A very well designed food for all kids","image":"","mealType":"LUNCH","unitPrice":30,"status":"ENABLED"},{"id":46,"name":"Gari and Beans","description":"A very well designed food for all kidsss","image":"","mealType":"LUNCH","unitPrice":12,"status":"ENABLED"}],"menuCategory":{"id":2,"name":"hello"}}]
console.log(parent[0].menuCategory.id);
If the parent argument in the callEditMenu function is referring to the JSON you included then try parent[0].menuCategory.id
let arr = [{"id":67,"name":"Wednesday Menu","serveDate":"2019-06-12 00:00:00","expiryDate":"2019-06-12 16:11:00","status":"APPROVED","isEnabled":true,"meals":[{"id":45,"name":"Waakye, Gari and Wele","description":"A very well designed food for all kids","image":"","mealType":"LUNCH","unitPrice":30,"status":"ENABLED"},{"id":46,"name":"Gari and Beans","description":"A very well designed food for all kidsss","image":"","mealType":"LUNCH","unitPrice":12,"status":"ENABLED"}],"menuCategory":{"id":2,"name":"hello"}}]
for (let item of arr) {
if (item.hasOwnProperty("menuCategory")) {
console.log(item["menuCategory"]);
}
};
let res = arr.filter((item) => item && item.menuCategory);
console.log(res[0].menuCategory);
In case you need to find it dynamically. Above are two different ways
Considering there would be multiple items in your array of objects, you can iterate through each object to get the menuCategory name as
let obj = [
{
"id": 67,
"name": "Wednesday Menu",
"serveDate": "2019-06-12 00:00:00",
"expiryDate": "2019-06-12 16:11:00",
"status": "APPROVED",
"isEnabled": true,
"meals": [
{
"id": 45,
"name": "Waakye, Gari and Wele",
"description": "A very well designed food for all kids",
"image": "",
"mealType": "LUNCH",
"unitPrice": 30,
"status": "ENABLED"
},
{
"id": 46,
"name": "Gari and Beans",
"description": "A very well designed food for all kidsss",
"image": "",
"mealType": "LUNCH",
"unitPrice": 12,
"status": "ENABLED"
}
],
"menuCategory": {
"id": 2,
"name": "hello"
}
}
];
obj.forEach(elem => {
console.log(elem.menuCategory.name);
});