Javascript: How to loop through array of objects for post request for array property? - javascript

I have an array response and i need to pass post request data from that response. The response have nested array objects as well. So how to loop through those array objects into post api request key values ?
Response which i am getting is as below:
records = "data": [
{
"id": 1,
"title": "Black Panther",
"product_images": [
{
"id": 1,
"images": {
"id": 1,
"thumbnail_image": "/assets/1/image.jpg",
},
},
{
"id": 2,
"images": {
"id": 2,
"thumbnail_image": "/assets/2/image.jpg",
},
}
],
product_categories: [
{
"id": 1,
"categories": {
"id": 3,
"category_name": "Outdoor Sports"
}
}
]
}
]
Now i need to pass that product_images array object's images.thumbnail_image property into the post request key value.
records.map((element) => {
let data;
data = {
"id": element.id,
"name": element.title,
"image_files":
[
{
"url": "" // need to pass thumbnail_image value over here.
}
],
"product_category": {
"category_id": [1,2] // need to pass product_categories[i].categories.id value over here.
}
}
})
axios post API request is as below:
axios({
method: 'post',
url: 'api_url',
data: {
"products": data,
}
}).then((response) => {
console.log(response);
}).catch((error) => {
console.log(error)
});
P.S: I have tried to manage this issue with loop through into the image_files array as below but that is working.
"image_files": [
element.product_images.map((ele) => {
{
"url": ele.images.thumbnail_image
}
})
]
::Updated::
I also need to manage that category property into the post api request. I have tried like this way but it pass the [null] value
"category_id": lists.campaign_product_categories.map((element) => {
let arr = []
arr.push(element.categories.id)
}),

You can use a nested map statement with destructuring to achieve this.
let records = [ { "id": 1, "title": "Black Panther", "product_images": [ { "id": 1, "images": { "id": 1, "thumbnail_image": "/assets/1/image.jpg", }, }, { "id": 2, "images": { "id": 2, "thumbnail_image": "/assets/2/image.jpg", }, } ] } ];
let data = records.map(({id, title:name, product_images}) => (
{
id, name,
"image_files": product_images.map(({images:{thumbnail_image: url}})=>({
url
}))
}
));
console.log(data);

You can just map the sub array for each array element like so:
const records = [
{
id: 1,
title: "Black Panther",
product_images: [
{
id: 1,
images: {
id: 1,
thumbnail_image: "/assets/1/image.jpg",
},
},
{
id: 2,
images: {
id: 2,
thumbnail_image: "/assets/2/image.jpg",
},
},
],
},
];
const mapped = records.map((element) => ({
id: element.id,
name: element.title,
image_files: element.product_images.map((i) => ({
url: i.images.thumbnail_image,
})),
}));
console.log(mapped);

You need to run a map on the product images inner array to create the URL array
let apiResponses = records.data.map((dataElement) => {
let urls = dataElement.product_images.map((product_image) => {
return {"url": product_image.images.thumbnail_image}
})
return {
"id": dataElement.id,
"name": dataElement.title,
"image_files":
urls,
}
})
console.log(apiResponses[0])
Outputs
{
id: 1,
name: 'Black Panther',
image_files: [ { url: '/assets/1/image.jpg' }, { url: '/assets/2/image.jpg' } ]
}
Full code below
let records = {"data": [
{
"id": 1,
"title": "Black Panther",
"product_images": [
{
"id": 1,
"images": {
"id": 1,
"thumbnail_image": "/assets/1/image.jpg",
},
},
{
"id": 2,
"images": {
"id": 2,
"thumbnail_image": "/assets/2/image.jpg",
},
}
]
}
]}
let apiResponses = records.data.map((dataElement) => {
let urls = dataElement.product_images.map((product_image) => {
return {"url": product_image.images.thumbnail_image}
})
return {
"id": dataElement.id,
"name": dataElement.title,
"image_files":
urls,
}
})
console.log(apiResponses[0])

You forgot the return statement
records.map((element) => {
let data;
data = {
"id": element.id,
"name": element.title,
"image_files":
[
{
"url": "" // need to pass thumbnail_image value over here.
}
],
}
return data; // <------- this line
})

Related

How to Filter Nested Object Array Without affecting References in JavaScript

Just want to remove all the items other than 14 from the parentId: 1001 and add that item to another object.
I want to filter the array without affecting the source array.
var Data = [{
"id": 1001,
"text": "A",
"items": [
{ "id": 13, "text": "Thirteen" },
{ "id": 14, "text": "Fourteen" },
{ "id": 15, "text": "Fifteen", }
]
},
{
"id": 1002,
"text": "B",
"items": [
{ "id": 21, "text": "TwentyOne" },
{ "id": 22, "text": "TwentyTwo" },
{ "id": 23, "text": "TwentyThree", }
]
}
]
var childId = 14;
Data.items.filter((x) => {
return x.id != childId;
})
//this is affecting the source array (Data)
//after searching on internet found a solution
Data.items.filter((x) => {
return x.id childId;
}).map(function(x) {
return x
});
Your Data has no items property: it is an array, so you actually have Data[0].items, Data[1].items, ...
NB: it is common practice to use camelCase for such variable names, and reserve PascalCase for constructors/classes
Here is how you could do it:
const data = [{"id": 1001,"text": "A","items": [{ "id": 13, "text": "Thirteen" }, { "id": 14, "text": "Fourteen" }, { "id": 15, "text": "Fifteen", }]},{"id": 1002,"text": "B","items": [{ "id": 21, "text": "TwentyOne" }, { "id": 22, "text": "TwentyTwo" }, { "id": 23, "text": "TwentyThree", }]}]
const childId = 14;
const newData = data.map(obj => ({
...obj,
items: obj.items.filter(x => x.id != childId)
}));
console.log(newData);
As you want to filter out a few items from an array object and want to add those into another object.
You can also achieve this requirement by doing a deep copy of an original array with the help of structuredClone() API and then iterating it using Array#forEach method.
Live demo :
const data=[
{
"id":1001,
"text":"A",
"items":[
{
"id":13,
"text":"Thirteen"
},
{
"id":14,
"text":"Fourteen"
},
{
"id":15,
"text":"Fifteen",
}
]
},
{
"id":1002,
"text":"B",
"items":[
{
"id":21,
"text":"TwentyOne"
},
{
"id":22,
"text":"TwentyTwo"
},
{
"id":23,
"text":"TwentyThree",
}
]
}
];
const clone = structuredClone(data);
let remainingItems = [];
clone.forEach(obj => {
if (obj.id === 1001) {
remainingItems = obj.items.filter(({ id }) => id !== 14);
obj.items = obj.items.filter(({ id }) => id === 14);
} else {
obj.items = [...obj.items, ...remainingItems];
}
})
console.log('cloned data_____', clone);
console.log('source data_____', data);

If the 'id' key is duplicated among the objects in the array, how to delete the object [duplicate]

This question already has answers here:
How to remove all duplicates from an array of objects?
(77 answers)
Closed 4 months ago.
If the 'id' key is duplicated among the objects in the array, how to delete the object
I tried using filter, map, and set, but it doesn't work.
It's not a one-dimensional array, so I don't know how to do it.
as-is
"category": {
"key": 1,
"order": 1,
"list": [
{
"id": "12345",
...
},
{
"id": "12345",
...
},
{
"id": "67890",
...
},
]
}
to-be
"category": {
"key": 1,
"order": 1,
"list": [
{
"id": "12345",
...
},
{
"id": "67890",
...
},
]
}
We iterate over that list using reduce function, then we checked whether the key we are accessing is visited or not with keys parameter of reduce method, and if it's not visited then we just push that object to a filtered array and returning keys array to keep it updated.
const data = {
"category": {
"key": 1,
"order": 1,
"list": [{
"id": "12345"
},
{
"id": "12345"
},
{
"id": "67890"
},
]
}
}
let filtered = [];
data.category.list.reduce((keys, currentObject) => {
if (!keys.includes(currentObject.id)) { //checking if current oject id is present in keys or not
// if not present than we will just push that object in
keys.push(currentObject.id);
//getting filttered object
filtered.push(currentObject);
}
return keys; //returning keys to update it
}, [])
data.category.list = filtered; //updating list
console.log(data);
A solution based on #Nick's comment
let data ={
"category": {
"key": 1,
"order": 1,
"list": [
{
"id": "12345"
},
{
"id": "12345"
},
{
"id": "67890"
},
]
}
}
let uniq = data.category.list.filter((o,i,a) => a.findIndex(o2 => o2.id == o.id) == i)
data.category.list = uniq
console.log(data)
You can use a set to track if id
const category = [{
"category": {
"key": 1,
"order": 1,
"list": [{
"id": "12345",
},
{
"id": "12345",
},
{
"id": "67890",
},
]
}
}]
const z = category.map(elem => {
const set = new Set()
return {
...elem,
category: {
...elem.category,
list: elem.category.list.reduce((acc, curr) => {
if (!set.has(curr.id)) {
set.add(curr.id);
acc.push(curr)
}
return acc;
}, [])
}
}
});
console.log(z)

How to filtering out the multiple nested object in Javascript object

Javascript
I have a nested array of objects, I'm trying to filter the given array of objects using a property from the third level of its array property value. For example, from the below array I like to filter the entire array using the property ListId: 10
Example
let test = {
"test":true,
"group":[
{
"name":"header",
"value":[
{
"id":"0",
"list":[
{
"ListId":10,
"name":"string1",
"state":"BY",
"techId":0
},
{
"ListId":11,
"name":"string2",
"state":"BY"
},
{
"ListId":12,
"name":"string3",
"state":"BY"
}
]
}
]
},
{
"name":"header2",
"value":[
{
"id":"01",
"list":[
{
"ListId":100,
"name":"string1",
"state":"BY",
"techId":0
},
{
"ListId":111,
"name":"string2",
"state":"BY"
},
{
"ListId":121,
"name":"string3",
"state":"BY"
}
]
}
]
}
]
}
Filtervalue with ListId = 10
Expected output :
{
"test":true,
"group":[
{
"name":"header",
"value":[
{
"id":"0",
"list":[
{
"ListId":10,
"name":"string1",
"state":"BY",
"techId":0
}
]
}
]
}
]
}
How can I use the filter method using javascript to get this expected result?
You can two it in two times :
First, filter the list arrays,
Secondly filter the groups array using the some method
let test= {
"test": true,
"group": [
{
"name": "header",
"value": [
{
"id": "0",
"list": [
{
"ListId": 10,
"name": "string1",
"state": "BY",
"techId": 0
},
{
"ListId": 11,
"name": "string2",
"state": "BY"
},
{
"ListId": 12,
"name": "string3",
"state": "BY"
}
]
}
]
},
{
"name": "header2",
"value": [
{
"id": "01",
"list": [
{
"ListId": 100,
"name": "string1",
"state": "BY",
"techId": 0
},
{
"ListId": 111,
"name": "string2",
"state": "BY"
},
{
"ListId": 121,
"name": "string3",
"state": "BY"
}
]
}
]
}
]
}
test.group.forEach(group => {
group.value.forEach(value => {
value.list = value.list.filter(list => list.ListId === 10)
})
})
test.group = test.group.filter(group => group.value.some(value => value.list.length > 0))
console.log(test)
Note : You should use plural names for you arrays, it helps understanding the data. For example lists not list for the array.
let z ={"group1": [
{
"name": "header",
"value": [
{
"id": 0,
"list": [
{
"ListId": 10,
"Name": "string1"
},
{
"ListId": 11,
"Name": "string2"
}
]
}
]
}
]}
// This function was written from understading that 'group1' is not a fixed property, but part of a dynamic list due to the number '1'
const getItemByListId = (list, listId) => {
const listKeys = Object.keys(list);
const selectedListKey = listKeys.find(key => {
const groupItems = list[key];
const selectedItem = groupItems.find(({ value: nestedItems }) => {
const selectedNestedItem = nestedItems.find(({ list }) => {
const selectedList = list.find(({ ListId }) => ListId === listId)
return selectedList;
});
return selectedNestedItem;
});
return selectedItem;
});
if (!selectedListKey) {
return null;
}
return list[selectedListKey];
};
console.log(getItemByListId(z, 10));

Put JSON data inside another object of the same JSON

I need to put the images that are on "included" into "data:{relationships: { field_imagen: { data" but the problem is that i just managed to put only the first image into every index using map and find
noticiasImages.forEach(function(data: { relationships: { field_imagen: {data: {id:any}}}} ) {
var nestedArray = noticiasData.map((noticiasImages: { id: any; }) => noticiasImages == noticiasData);
data = nestedArray && noticiasImages || noticiasData;
});
And this is my json (example node)
{
"data": [
"relationships": {
"field_imagen": {
"data": [
{
"type": "file--file",
"id": "dba917f0-b80f-45ed-a569-69f2ba2b482d",
}
],
}
]
},
this is the included object, who is in the same level as data
"included": [
"attributes": {
"drupal_internal__fid": 8798,
"langcode": "es",
"filename": "_DSC6472 - copia.jpg",
"uri": {
"value": "public:\/\/2019-11\/_DSC6472 - copia.jpg",
"url": "\/sites\/default\/files\/2019-11\/_DSC6472%20-%20copia.jpg"
},
},
,
Expected Result:
"data": [
"relationships": {
"type": "node--actualidad_institucional",
"id": "71514647-af49-4136-8a28-9563d133070a",
"field_imagen": {
"data": [
{
"type": "file--file",
"id": "dba917f0-b80f-45ed-a569-69f2ba2b482d",
"uri": {
"value": "public:\/\/2019-11\/_DSC6472 - copia.jpg",
"url": "\/sites\/default\/files\/2019-11\/_DSC6472%20-%20copia.jpg"
},
}
}
},
I put the uri from included into field_imagen. Tried to resolve like that, but it just put only the first image of the Array from the included object in every node:
showNoticias() {
this.frontService.getNoticias()
.subscribe((data: Noticias) => {
this.noticiasImages = Array.from(data.included);
this.noticiasData = Array.from(data.data);
let noticiasImages = this.noticiasImages.map((data: {id: any}) => data.id);
let noticiasData = this.noticiasData.map((data:{relationships: { field_imagen: { data: { id: any; }}}}) => data.relationships.field_imagen.data.id);
noticiasImages.forEach(function(data: { relationships: { field_imagen: {data: {id:any}}}} ) {
var nestedArray = noticiasData.map((noticiasImages: { id: any; }) => noticiasImages == noticiasData);
data = nestedArray && noticiasImages || noticiasData;
});
console.log(data);
});
}
Hope you can help me, thanks!
UPDATE: tried that but didnt work like expected
let merged = data.data.map((data:{relationships: { field_imagen: { data: any }}}) => Object.assign({}, noticiasImages));
console.log(data)
console.log(merged)
Sometimes using regular for loops are a better option. Using map with objects that have that many properties can get confusing. And using forEach will not give you access to the i index of the iteration in the loop, which makes things easier in this case.
for (let i = 0; i < obj.included.length; i++) {
let uri = obj.included[i].attributes.uri;
obj.data[i].relationships.field_imagen.data[0] = {
...obj.data[i].relationships.field_imagen.data[0],
...uri
}
}
console.log(obj)
Output:
{
"data": [
{
"relationships": {
"field_imagen": {
"data": [
{
"type": "file--file",
"id": "dba917f0-b80f-45ed-a569-69f2ba2b482d",
"value": "public://2019-11/_DSC6472 - copia.jpg",
"url": "/sites/default/files/2019-11/_DSC6472%20-%20copia.jpg"
}
]
}
}
}
],
"included": [
{
"attributes": {
"drupal_internal__fid": 8798,
"langcode": "es",
"filename": "_DSC6472 - copia.jpg",
"uri": {
"value": "public://2019-11/_DSC6472 - copia.jpg",
"url": "/sites/default/files/2019-11/_DSC6472%20-%20copia.jpg"
}
}
}
]
}

Filtering array of objects by an out of order array of IDs in Javascript

Here's an array of book objects.
const books=[
{
"id": 1,
"title": "NPR",
"url": "https://www.npr.org"
},
{
"id": 2,
"title": "Google Docs",
"url": "https://docs.google.com/"
},
{
"title": "Fetch API Docs",
"url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",
"id": 3
},
{
"title": "Yahoo",
"url": "http://www.yahoo.com",
"id": 4
},
{
"title": "Google",
"url": "http://www.google.com",
"id": 5
}
]
And a separate array of IDs
const selectedIds = [1, 5, 3]
With javascript, how can I filter the books array to just the selectedIds (keeping the same order as in selectedIds)?
Final result I'm looking to get:
selectedBooks = [
{
"id": 1,
"title": "NPR",
"url": "https://www.npr.org"
},
{
"title": "Google",
"url": "http://www.google.com",
"id": 5
},
{
"title": "Fetch API Docs",
"url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",
"id": 3
}
]
My current code is like this but this preserves the order of the books array (i.e. [1, 3, 5]):
books.filter(function(item) {
return selectedIds.includes(item.id);
}
Go in the other direction.
selectedIds.map(id => books.find(b => b.id === id))
const books = [{
id: 1,
title: "NPR",
url: "https://www.npr.org"
},
{
id: 2,
title: "Google Docs",
url: "https://docs.google.com/"
},
{
title: "Fetch API Docs",
url: "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch",
id: 3
},
{
title: "Yahoo",
url: "http://www.yahoo.com",
id: 4
},
{
title: "Google",
url: "http://www.google.com",
id: 5
}
];
const selectedIds = [1, 5, 3];
const mapped = selectedIds.map(id => {
return books.find(book => book.id === id);
});
console.log(mapped);

Categories