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];
}
Related
My database looks like this:
[
{
"title": "man",
"articlesType": [
{
"title": "shoes",
"articles": [
{
"title": "shoes1",
"id": "randomId"
},
{
"title": "shoes2",
"id": "alsoRandomId"
}
]
}
]
},
{
"title": "woman",
"articlesType": [
{
"title": "pants",
"articles": [
{
"title": "pants1",
"id": "anotherRandomId"
},
{
"title": "pants1",
"id": "justId"
}
]
}
]
}
]
I expect something like this: , is it possible to get whole object in this nested just using an ID?
{
"title": "shoes2",
"id": "alsoRandomId"
}
I found this, but does not work for me
You can try an aggregation pipeline using double $unwind to deconstruct the array twice and then filter by your desired id (I'm assuming you want to match by the id).
And the last step, $project is to output the result in the same way as you want.
db.collection.aggregate([
{
"$unwind": "$articlesType"
},
{
"$unwind": "$articlesType.articles"
},
{
"$match": {
"articlesType.articles.id": "alsoRandomId"
}
},
{
"$project": {
"title": "$articlesType.articles.title",
"id": "$articlesType.articles.id"
}
}
])
Example here
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 ;)!
I have used JSON stringify and JSON Parse etc..., but I'm having trouble with finding /figuring how how to split up my JSON result into multiple variables.
Issue: I have a JSON result with 2 to many results (sections, pages etc...)
Goal : To store each result /row into its own variable.
Example of FULL unparsed JSON result:
{
"pages": [
{
"name": "page1",
"elements": [
{
"type": "text",
"name": "question1"
}
]
},
{
"name": "page2",
"elements": [
{
"type": "checkbox",
"name": "question2",
"choices": [
"item1",
"item2",
"item3"
]
}
]
}
]
}
In the example, notice that "name": "page1" and page2 are the clear separators, I could end up having them calling SectionA , SectionB etc.. but that shouldn't be important.
I need to store them separately
I also need to maintain that complete JSON structure
example of what i want to do with it
var page1 =
{
"pages": [
{
"name": "page1",
"elements": [
{
"type": "text",
"name": "question1"
}
]
}
]
}
2nd one:
var page2 =
{
"pages": [
{
"name": "page2",
"elements": [
{
"type": "checkbox",
"name": "question2",
"choices": [
"item1",
"item2",
"item3"
]
}
]
}
]
}
Notice that not only is it broken apart, but the main part I want to have maintained in the variable "pages: [
Just a simple map() operation would do it.
Afterwards you can use array destructuring to capture your result into separate variables:
const data = {
"pages": [{
"name": "page1",
"elements": [{
"type": "text",
"name": "question1"
}]
},
{
"name": "page2",
"elements": [{
"type": "checkbox",
"name": "question2",
"choices": [
"item1",
"item2",
"item3"
]
}]
}
]
};
const split = data.pages.map(p => ({pages: [p]}));
console.log(split);
const [page1, page2] = split;
console.log(page1);
console.log(page2);
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])
This is a follow up question for Compare two arrays and update with the new values by keeping the existing objects using javascript which was ansewered by #Siderite Zackwehdex
Please check this plunker I'm getting the deleted Object in the changedArray1.Is there any option to fix this.Its working fine for other changes like add,update but not for delete.
One feature that I tried to implement is to add an additional object ie., "removedIds":[23] , that holds the deleted id's as an array in each level of objects and identifying them in the evaluation process.. but didn't find the right soultion
Example data:
var parentArray1=[
{
"id": 1,
"name": "test",
"context": [
{
"operationalContextId": 1.1,
"valueChainEntityDetails": [
{
"valuChainEntityId": 3,
"name": "test",
"context": [
{
"id": 3.1,
"name": "test 3.1",
"activityDetails": [
{
"activityId": 22,
"name": "test 3.1"
},
{ //trying to remove activity id 23
"activityId": 23,
"name": "changed test 23"
}
]
}
]
}
]
}
]
}
]
var changedArray1=[
{
"id": 1,
"name": "test2",
"context": [
{
"operationalContextId": 1.1,
"valueChainEntityDetails": [
{
"valuChainEntityId": 3,
"name": "changed test3",
"context": [
{
"id": 3.1,
"name": "test 3.1",
"removedIds":[23] ,
"activityDetails": [ //activity id 23 is removed in this JSON but reflecting in parentArray1
{
"activityId": 22,
"name": "changed test 3.1"
}
]
}
]
}
]
}
]
}
]