javascript - 如何从 json 数组生成键/值的每个组合?

标签 javascript arrays json

我有一个随机的 json 键值数组,其中值是这样的数组:

json = {foo:[1,2],bar:[3,4],pi:[5]}

我怎样才能为任意数量的键生成这些参数的每个组合,这样我就可以得到如下列表:

{foo:1,bar,3,pi:5}
{foo:1,bar:4,pi:5}
{foo:2,bar:3,pi:5}
{foo:2,bar:4,pi:5}

最佳答案

使用 reduce 并为每次迭代生成新的排列:

const json = {foo:[1,2],bar:[3,4],pi:[5, 7], test: [1]};

const results = Object.keys(json).reduce((acc, key) => {
  const newArray = [];
  
  json[key].forEach(item => {
    if (!acc || !acc.length) { // First iteration
      newArray.push({[key]: item});
    } else {
      acc.forEach(obj => {
        newArray.push({...obj, [key]: item});
      });
    }
  });
  
  return newArray;
}, []);

console.log(results);

关于javascript - 如何从 json 数组生成键/值的每个组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47934966/

相关文章:

javascript - 每 2 项新行

javascript - POST 请求返回 text/html 而不是 JSON,如何在 JS 中获取 JSON?

java - 错误 : exception in thread 'main' java. lang.ArrayIndexOutOfBoundsException: 0

JavaScript - 使用变量创建嵌套值

javascript - 使用 Javascript/JQuery 的 JSON 对象的区别

php - $response JSON 只返回 1 行,PHP,ANDROID

c# - JSON.parse Html 内容

Javascript/JSON : Object of object converted to associative array

ios - 根据条件 Swift 获取模型对象的特定属性数组

c# - 如果元素计数小于 'n',则删除数组中的所有相似元素