【问题标题】:array of arrays conversion in JavascriptJavascript中的数组转换
【发布时间】:2022-01-20 15:06:18
【问题描述】:

我需要创建一个数组数组。 值得注意的是,数据库非常大,如果任何属性没有对应的值,它会发送一个空字符串。我尝试过使用 map 和 reduce,但没有成功:

任何帮助将不胜感激。

下面我展示了一个预期输出的例子:

outputExpected = [
  ["id", 1, 2],
  ["name", "name1", "name2"],
  ["price", 6.95, 998.95],
  ["promoPrice", 5.91, 333.91],
  ["category", "test1 | test2", "test3 | test4"],
]

有什么方法可以在性能上解决这个问题?

这是我的代码:

let arrayObj = [{
    "id": 1,
    "name": "name1",
    "price": 6.95,
    "promoPrice": 5.91,
    "category": ["test1, test2"]
  },
  {
    "id": 2,
    "name": "name2",
    "price": 998.95,
    "promoPrice": 333.91,
    "category": ["test3, test4"]
  }
]

const headers = ["id", "name", "price", "promoPrice", "category"]
const result1 = headers.concat(arrayObj.map((obj) => {
  return headers.reduce((arr, key) => {
    arr.push(obj[key]) return arr;
  }, [])
}))

console.log(result1)

【问题讨论】:

  • 显示您尝试过的内容,然后我们将展示如何修复它。我们不会为你写的。
  • 这是我的代码: const headers = ["id","name","price","promoPrice", "category"] const result1 = headers.concat(arrayObj.map((obj ) => { return headers.reduce((arr, key) => { arr.push(obj[key]) return arr; }, []) }))
  • 在问题中添加您的代码。使用edit

标签: javascript arrays json object reduce


【解决方案1】:

将数组简化为 Map。在每次迭代中,使用Object.entries() 将对象转换为[key, value] 对的数组。使用Array.forEach() 迭代条目并将它们添加到地图中。使用 Array.from() 将 Map 的值迭代器转换为数组:

const arr = [{"id":1,"name":"name1","price":6.95,"promoPrice":5.91,"category":["test1", "test2"]},{"id":2,"name":"name2","price":998.95,"promoPrice":333.91,"category":["test3", "test4"]}]

const result = Array.from(arr.reduce((acc, o) => {
  Object.entries(o)
    .forEach(([k, v]) => {
      if(!acc.has(k)) acc.set(k, [k])
      
      acc.get(k).push(Array.isArray(v) ? v.join(' | ') : v)
    })
  
  return acc
}, new Map()).values())

console.log(result)

【讨论】:

  • 以同样的方法,我如何在预期输出中考虑新属性?我想连接字符串“name[i]: values[i]”。我被困在这一步了。再次感谢!
  • 请打开一个新问题
  • 我编辑了这个。够了吗?
  • 这个问题已经完成了。将其恢复到以前的状态,然后打开一个新问题。
【解决方案2】:

您可以简单地映射值并检查项目是否为数组,然后获取连接的值或值本身。

const
    data = [{ id: 1, name: "name1", price: 6.95, promoPrice: 5.91, category: ["test1, test2"] }, { id: 2, name: "name2", price: 998.95, promoPrice: 333.91, category: ["test3, test4"] }],
    headers = ["id", "name", "price", "promoPrice", "category"],
    result = data
        .reduce(
            (r, o) => headers.map((k, i) => [
                ...r[i],
                Array.isArray(o[k]) ? o[k].join(' | ') : o[k]
            ]),
            headers.map(k => [k]),
        );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案3】:

    使用所需顺序的所有可能键构造一个init 数组,然后根据其索引为每个键使用Array.reduceArray.forEachArray.push 值。

    const arrayObj = [
      {
      "id":1,
      "name":"name1",
      "price":6.95,
      "promoPrice":5.91,
      "category":["test1", "test2"]
      },
      {
        "id":2,
        "name":"name2",
        "price":998.95,
        "promoPrice":333.91,
        "category":["test3", "test4"]
      }
    ]
    
    function ConvertToArray2D (items) {
      let init = [['id'], ['name'], ['price'], ['promoPrice'], ['category']]
      if (!items) return init
      return arrayObj.reduce((pre, cur) => {
        init.forEach((key, index) => {
          pre[index].push(Array.isArray(cur[key[0]]) ? cur[key[0]].join('|') : cur[key[0]])
        })
        return pre
      }, init.slice())
    }
    console.log(ConvertToArray2D(arrayObj))

    【讨论】:

      【解决方案4】:

      在将您的对象映射到符合headers 数组的值数组后,可以使用标准“zip”来处理。 (这也允许返回结果)。

      //** @see https://stackoverflow.com/a/10284006/13762301
      const zip = (...rs) => [...rs[0]].map((_, c) => rs.map((r) => r[c]));
      
      const headers = ['id', 'name', 'price', 'promoPrice', 'category'];
      const arrayObj = [{ id: 1, name: 'name1', price: 6.95, promoPrice: 5.91, category: ['test1', 'test2'] },{ id: 2, name: 'name2', price: 998.95, promoPrice: 333.91, category: ['test3', 'test4'] },];
      
      const result = zip(
        headers,
        ...arrayObj.map((o) => headers.map(h => Array.isArray(o[h]) ? o[h].join(' | ') : o[h]))
      );
      
      console.log(result);
      
      // which also allows it to be reversed
      console.log(zip(...result));
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      请参阅:Javascript equivalent of Python's zip function 以了解进一步的 zip 讨论。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-14
        • 1970-01-01
        • 1970-01-01
        • 2017-11-14
        • 1970-01-01
        • 2018-12-17
        • 2013-08-06
        • 1970-01-01
        相关资源
        最近更新 更多