首页 > 解决方案 > 将对象中的数组转换为单个字符串

问题描述

我怎样才能在一个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
}]

标签: javascript

解决方案


您可以尝试使用类似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'))


推荐阅读