I'm trying to pull out the individual images in the "images" object below under "details" section.
Seem to just be getting nothing printing out. Looking for the correct way to pull within the details.images.image1,2, or 3.
Here is the JSON data I'm working with so far:
{
"books": [
{
"title": "title 1",
"image": "/image1.jpg"
},
{
"title": "title 2",
"image": "/image2.jpg"
}
],
"details": [
{
"author": "book author",
"name": "Book name",
"price": 34.99,
"publisher": "Penguin Books",
"images": [
{
"image1": "/image1.jpg",
"image2": "/image2.jpg",
"image3": "/image3.jpg"
}
]
}
]
}
Also here is the JSON call I'm making in a Book component:
{staticdata.details.map(detail => (
<Book
book_name={detail.author}
book_price={detail.price}
image={detail.images.image1}
/>
))}
Here's an example of accessing those nested properties and logging them to the console. It appears your attempt was mostly correct, but images is an array.
const data = {
"books": [
{
"title": "title 1",
"image": "/image1.jpg"
},
{
"title": "title 2",
"image": "/image2.jpg"
}
],
"details": [
{
"author": "book author",
"name": "Book name",
"price": 34.99,
"publisher": "Penguin Books",
"images": [
{
"image1": "/image1.jpg",
"image2": "/image2.jpg",
"image3": "/image3.jpg"
}
]
}
]
}
data.details.map(detail => {
console.log(detail.author, detail.price, detail.images[0].image1);
});
Related
How would you group an array by a property of the objects in a nested array. Either vanilla or lodash.
For example, how would you group an array of tasks by the assignee, when tasks can have more than one person assigned.
Example data:
[
{
"assignees": [
{
"name": "John",
"uid": "id0001"
},
{
"name": "Sally",
"uid": "id0002"
}
],
"title": "Task 1",
"status": "To do"
},
{
"assignees": [
{
"name": "John",
"uid": "id0001"
}
],
"title": "Task 2",
"status": "To do"
},
{
"assignees": [
{
"name": "Sally",
"uid": "id0002"
}
],
"title": "Task 3",
"status": "To do"
}
]
Example desired result:
{
"id0001": {
"name": "John",
"tasks": [
{
"title": "Task 1",
"status": "To do"
},
{
"title": "Task 2",
"status": "To do"
}
]
}
},
{
"id0002": {
"name": "Sally",
"tasks": [
{
"title": "Task 1",
"status": "To do"
},
{
"title": "Task 3",
"status": "To do"
}
]
}
}
I have a lot of things both vanilla and lodash - a simple example is below. I was expecting an array of three groups. One for Sally, one for John and one for Sally and John:
const grouped = _.groupBy(taskList, (task) => task.assignees);
But that returns one group [object Object] with all the tasks in it.
Since uids are unique, the Array seems like an overhead.
I suggest to get an Object literal with the tasks grouped by the user's uids: like:
{
id0001: {...user, tasks: []},
id0002: {...user, tasks: []},
}
Example:
const groupTasksByUserId = (arr) => arr.reduce((ob, {assignees, ...task}) => {
assignees?.forEach((user) => {
ob[user.uid] ??= {...user, tasks: []};
ob[user.uid].tasks.push(task)
});
return ob;
}, {});
const data = [{
"assignees": [{"name": "John", "uid": "id0001"}, {"name": "Sally","uid": "id0002"}],
"title": "Task 1",
"status": "To do"
}, {
"assignees": [{"name": "John", "uid": "id0001"}],
"title": "Task 2",
"status": "To do"
}, {
"assignees": [{"name": "Sally", "uid": "id0002"}],
"title": "Task 3",
"status": "To do"
}];
const res = groupTasksByUserId(data);
// console.log(res);
console.log(JSON.stringify(res, 0, 2));
Find out more about the above used Array methods (reduce and forEach) on MDN Docs
I'm a bit new with javascript. Is there a way to find all icon and get their value and then replace their values with a new one?
I need to replace all of fa/FaCopy with fcb/FcbCopy in the json payload below. Any libraries or functions you can share?
[
{
"section": "feature-list",
"data": {
"title": "Title here",
"body": "body here",
"features": [
{
"title": "Title here 1",
"image": "body here",
"icon": "fa/FaCopy"
},
{
"title": "Title here 2",
"image": "body here",
"icon": "fa/FaCopy"
},
{
"title": "Title here 3",
"image": "body here",
"icon": "fa/FaCopy"
}
]
}
},
{
"section": "title-list",
"data": {
"title": "Title here",
"titles": {
"list": [
{
"title": "Title here 1",
"icon": "fa/FaCopy"
},
{
"title": "Title here 2",
"icon": "fa/FaCopy"
},
{
"title": "Title here 3",
"icon": "fa/FaCopy"
}
]
}
}
}
]
This will be very customized solution and deeply depended on your data.
If your data type will not change and remain same then you could use/modify something like this.
// DATA = Your array
const result = DATA.map((list) => ({
...list,
data: {
...list.data,
features: list.data.features?.map((feature) => ({
...feature,
icon: feature.icon === 'fa/FaCopy' ? 'fcb/FcbCopy' : feature.icon
})),
},
}));
console.log(result); // your expected result
I have object like this:
{
"id": 1,
"name": "first",
"sections": [
{
"id": 1,
"title": "First section",
"contents": [
{
"id": "123",
"title": "Sample title 1",
"description": "<html>code</html>",
},
{
"id": "124",
"title": "Sample title 2",
"description": "<html>code</html>"
},
{
"id": "125",
"title": "Some other sample",
"description": "<html>code</html>"
}
]
},
{
"id": 2,
"title": "Second section",
"contents": [
{
"id": "126",
"title": "Sample title 126",
"description": "<html>code</html>"
},
{
"id": "127",
"title": "Sample title 127",
"description": "<html>code</html>"
}
]
}
]
}
I want to remove specific object from contents array by its id (all those ids are unique).
I can easily find element I want to remove, but I'm unable to find in which section this element is to splice it later.
obj.sections.forEach(function(section) {
section.contents.forEach((content) => {
if (content.id == 125) {
console.log(content)
console.log(section)
}
})
})
In above code console.log(sections) returns undefined. How can I get position in sections array which contains contents array that has specific id. For example, id: 125 would return sections position 0, so I can use splice to remove that element.
If my approach is completely wrong please point me in right direction, thanks :)
You could use .filter() instead of .splice(). .filter() will keep all items which you return true for and discard of those which you return false for. So, if the current section's content's object has an id equal to the one you want to remove you can return false to remove it, otherwise return true to keep that item. You can use this with .map() to map each section object to a new one with an updated contents array:
const obj = { "id": 1, "name": "first", "sections": [ { "id": 1, "title": "First section", "contents": [ { "id": "123", "title": "Sample title 1", "description": "<html>code</html>", }, { "id": "124", "title": "Sample title 2", "description": "<html>code</html>" }, { "id": "125", "title": "Some other sample", "description": "<html>code</html>" } ] }, { "id": 2, "title": "Second section", "contents": [ { "id": "126", "title": "Sample title 126", "description": "<html>code</html>" }, { "id": "127", "title": "Sample title 127", "description": "<html>code</html>" } ] } ] };
const idToRemove = 125;
obj.sections = obj.sections.map(
sec => ({...sec, contents: sec.contents.filter(({id}) => id != idToRemove)})
);
console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore */
Why not use a simple filter for accomplishing the task. Also, it will be much cleaner and immutable way of doing it.
let newArrWithoutContentWithGivenId = obj.sections.map(section =>
({...section, contents: section.contents.filter(content =>
content.id != 125)}));
Here, we are mapping each section whose content does not contain the ID 125. In short, section > content.id != 125 will be removed from the new array.
Hope it helps :)
Note: Code is not tested, it is just to help you find a way to do it cleanly.
You only need to use the second argument of forEach :)
obj.sections.forEach(function(section, sectionIndex) {
section.contents.forEach((content, contentIndex) => {
if (content.id == 125) {
// use the sectionIndex and contentIndex to remove
}
})
})
Here's an example of object from the JSON output of my database:
{
"id": "http://...",
"type": "example-type",
"title": "Example title",
"container-title": "Example container title",
"page": "1-100",
"issue": "3",
"URL": "http://www.url",
"ISSN": "0123-0123",
"author": [
{
"family": "Smith",
"given": "John"
}
],
"issued": {
"date-parts": [
[
"2000"
]
]
},
"keyword": "Sample Tag"
}
I've had enormous difficulties/bugs referring to the nested fields for author and date when building a data table. What I would like to do is somehow modify/flatten this before using it in the table (using Datatables' dataSrc as described here) and then simply call the restructured data as many times as I need using the datatables API.
So what I now refer to as issued.date-parts.0.0 would be simply year. The structure would be instead:
"authors": "John Smith", "Mark Smith"
"year": "2000"
Use the map function to get the authors
Look at this code snippet
var data = { "id": "http://...", "type": "example-type", "title": "Example title", "container-title": "Example container title", "page": "1-100", "issue": "3", "URL": "http://www.url", "ISSN": "0123-0123", "author": [ { "family": "Smith", "given": "John" }, { "family": "Smith", "given": "Mark" } ], "issued": { "date-parts": [ [ "2000" ] ] }, "keyword": "Sample Tag"};
var result = {
"authors": data.author.map((d) => `${d.given} ${d.family}`),
"year": data.issued['date-parts'][0][0]
}
console.log(result);
.as-console-wrapper {
max-height: 100% !important
}
I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?
You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }