gpt4 book ai didi

Javascript:如何遍历对象数组以发布对数组属性的请求?

转载 作者:行者123 更新时间:2023-12-04 09:15:02 35 4
gpt4 key购买 nike

我有一个 array响应,我需要从该响应传递发布请求数据。响应也有嵌套的数组对象。那么如何将这些数组对象循环到 post api 请求键值中呢?
我得到的回应如下:

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"
}
}
]
}
]
现在我需要通过 product_images数组对象的 images.thumbnail_image属性添加到发布请求键值中。
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 请求如下:
axios({
method: 'post',
url: 'api_url',
data: {
"products": data,
}
}).then((response) => {
console.log(response);
}).catch((error) => {
console.log(error)
});
P.S:我试图通过循环进入 image_files 来管理这个问题。数组如下,但这是有效的。
"image_files": [
element.product_images.map((ele) => {
{
"url": ele.images.thumbnail_image
}
})
]
::更新::
我还需要将该类别属性管理到 post api 请求中。我试过这样,但它通过了 [null]值(value)
"category_id": lists.campaign_product_categories.map((element) => {
let arr = []
arr.push(element.categories.id)
}),

最佳答案

您可以使用嵌套的 map声明与解构来实现这一点。

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);

关于Javascript:如何遍历对象数组以发布对数组属性的请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63267239/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com