javascript - 将对象中的数组转换为单个字符串
问题描述
我怎样才能在一个array
之间拆分images
一个object
?
例如,使用下面的JSON。如何产生return
string
每个itemUrl
和它的关联productCode
?
这个 JSON
{
"products": [
{
"productCode": "ID1",
"images": [
{
"id": 1,
"itemUrl": "https://img.com/1.JPG"
},
{
"id": 2,
"itemUrl": "https://img.com/2.JPG"
}
]
},
{
"productCode": "ID2",
"images": [
{
"id": 3,
"itemUrl": "https://img.com/3.JPG"
},
{
"id": 4,
"itemUrl": "https://img.com/4.JPG"
},
{
"id": 5,
"itemUrl": "https://img.com/5.JPG"
}
]
}
]
}
变成
https://img.com/1.JPG
https://img.com/2.JPG
https://img.com/3.JPG
https://img.com/4.JPG
https://img.com/5.JPG
目前,如果我要使用
for (const tour of data.products) {
console.log(tour.images[0].itemUrl);
...
回报显然会return
https://img.com/1.JPG
https://img.com/3.JPG
然而,当
let imageEach = tour.images;
let output = [];
imageEach.forEach(item => {
output.push(item.itemUrl);
});
...
我得到return
一个
[{
https://img.com/1.JPG,
https://img.com/2.JPG
}]
[{
https://img.com/3.JPG
https://img.com/4.JPG
https://img.com/5.JPG
}]
解决方案
您可以尝试使用类似Array.reduce
的方法来迭代产品并遍历Array.map
项目并获得itemUrl
:
const data = { "products": [ { "productCode": "ID1", "images": [ { "id": 1, "itemUrl": "https://img.com/1.JPG" }, { "id": 2, "itemUrl": "https://img.com/2.JPG" } ] }, { "productCode": "ID2", "images": [ { "id": 3, "itemUrl": "https://img.com/3.JPG" }, { "id": 4, "itemUrl": "https://img.com/4.JPG" }, { "id": 5, "itemUrl": "https://img.com/5.JPG" } ] } ] }
const result = data.products.reduce((r,{images}) => {
r.push(...images.map(x => x.itemUrl))
return r
}, [])
console.log(result.join('\n'))
或者甚至更短,正如@Prassana 所建议的,通过使用 ES6 数组传播更多:
const data = { "products": [ { "productCode": "ID1", "images": [ { "id": 1, "itemUrl": "https://img.com/1.JPG" }, { "id": 2, "itemUrl": "https://img.com/2.JPG" } ] }, { "productCode": "ID2", "images": [ { "id": 3, "itemUrl": "https://img.com/3.JPG" }, { "id": 4, "itemUrl": "https://img.com/4.JPG" }, { "id": 5, "itemUrl": "https://img.com/5.JPG" } ] } ] }
const result = data.products.reduce((r,{images}) =>
[...r, ...images.map(x => x.itemUrl)], [])
console.log(result.join('\n'))
推荐阅读
- javascript - 向空对象属性添加值
- nginx - Fail2ban Nginx-noscript 错误地禁止 ip
- reactjs - Microsoft Graph API REST 授权流 CORS 错误
- python - 从 crontab 在 virtualenv 中运行 python 方法
- google-analytics - 我可以在不设置“数据流”的情况下使用 Google 分析吗?
- qt - x2go / x2godesktopsharing 显示 qt.qpa.xcb:无法连接到显示器 / Mate 桌面
- r - 如何在 rdatatable 的“i”中传递名称向量?
- html - 如何使 div 大小独立于包含文本?
- javascript - 如何使用 blob 对象在 react js 中下载文件,featherjs 如何帮助将 blob 处理为“responseType”?
- angular - Angular Material 表头粘滞:true 不工作