如何提取嵌套的多级JSON对象/数组的部分并使用JavaScript将其展平

时间:2017-11-16 07:12:10

标签: javascript arrays json parsing multidimensional-array

我正在使用以下数据结构:

"data": {
    "products": [
        [
            {
                "category": "A",
                "items": [
                    {
                        "name": "Aloe",
                        "price": 10
                    },
                    {
                        "name": "Apples",
                        "price": 5
                    }
                ]
            },
            {
                "category": "B",
                "items": [
                    {
                        "name": "Bread",
                        "price": 5
                    }
                ]
            }
        ],
        [
            {
                "category": "C",
                "items": [
                    {
                        "name": "Candy",
                        "price": 5
                    },
                    {
                        "name": "Crayon",
                        "price": 5
                    }
                ]
            },
            {
                "category": "D",
                "items": [
                    {
                        "name": "Dice",
                        "price": 5
                    },
                    {
                        "name": "Doll",
                        "price": 10
                    }
                ]
            }
        ]
    ]
}

我想提取它的一部分来展平,结果如下:

[
    {
        "name": "Aloe",
        "price": 10
    },
    {
        "name": "Apples",
        "price": 5
    },
    {
        "name": "Bread",
        "price": 5
    },
    {
        "name": "Candy",
        "price": 5
    },
    {
        "name": "Crayon",
        "price": 5
    },
    {
        "name": "Dice",
        "price": 5
    },
    {
        "name": "Doll",
        "price": 10
    }
]

我该如何做到这一点?

我试过这个:

for (var sets in data.products) {
  for (var categories in sets) {
    for (var items in categories) {
      for (var item in items) { 
        // assemble new array 
      }
    }
  }
}

...但在循环子对象时遇到问题。我找到了其他几个similar questions,但它们似乎解决了更简单的数据结构,并且整理了整个对象而不是它的一部分。

任何指针都会受到赞赏。

5 个答案:

答案 0 :(得分:2)

def sumofsquares(x1):
    result = [] # list to store squares of each number

    for i in range(len(x1)): # iterating through the list
        result.append(x1[i] ** 2) # squaring each number and appending to the list

    return (sum(result)) # returning the sum of the list

product = [1, 2, 3] # declaring the array to find sum of sqaure
print (sumofsquares(product)) # calling the function and displaying the return value

# Output
14

maube第1行的更改取决于您的变量名称

input.data.products. ....

答案 1 :(得分:0)

你必须尝试这样的事情:

逻辑:

  • 循环data.products以获取单个产品详细信息。
  • 正弦细节也是数组,循环遍历它们并从它们返回items

诀窍是,你必须使用Array.prototype.concat来合并返回的数组,以展平它们。

var data = {
  "products": [
    [{
        "category": "A",
        "items": [{
            "name": "Aloe",
            "price": 10
          },
          {
            "name": "Apples",
            "price": 5
          }
        ]
      },
      {
        "category": "B",
        "items": [{
          "name": "Bread",
          "price": 5
        }]
      }
    ],
    [{
        "category": "C",
        "items": [{
            "name": "Candy",
            "price": 5
          },
          {
            "name": "Crayon",
            "price": 5
          }
        ]
      },
      {
        "category": "D",
        "items": [{
            "name": "Dice",
            "price": 5
          },
          {
            "name": "Doll",
            "price": 10
          }
        ]
      }
    ]
  ]
}

var result = [].concat.apply([], data.products.map(function(product){
  return [].concat.apply([], product.map(function(p){
    return p.items
  }))
}))

console.log(result)

答案 2 :(得分:0)

我先将数据的JSON对象分配给变量。请参阅以下代码:

var pro={
    "products": [
        [
            {
                "category": "A",
                "items": [
                    {
                        "name": "Aloe",
                        "price": 10
                    },
                    {
                        "name": "Apples",
                        "price": 5
                    }
                ]
            },
            {
                "category": "B",
                "items": [
                    {
                        "name": "Bread",
                        "price": 5
                    }
                ]
            }
        ],
        [
            {
                "category": "C",
                "items": [
                    {
                        "name": "Candy",
                        "price": 5
                    },
                    {
                        "name": "Crayon",
                        "price": 5
                    }
                ]
            },
            {
                "category": "D",
                "items": [
                    {
                        "name": "Dice",
                        "price": 5
                    },
                    {
                        "name": "Doll",
                        "price": 10
                    }
                ]
            }
        ]
    ]
}
var flatArray=[];
for(var i=0; i<pro.products.length; i++){
  for(var j=0; j<pro.products[i].length;j++){
    for(var k=0; k<pro.products[i][j].items.length;k++){
      flatArray.push(pro.products[i][j].items[k]);
    }
  }
}

flatArray将是您所需的扁平对象数组。希望这很清楚。

答案 3 :(得分:0)

您可以使用array#reducearray#forEacharray#concat

&#13;
&#13;
var input =  { data: { products: [[{ category: "A", items: [{ name: "Aloe", price: 10 }, { name: "Apples", price: 5 }] }, { category: "B", items: [{ name: "Bread", price: 5 }] }], [{ category: "C", items: [{ name: "Candy", price: 5 }, { name: "Crayon", price: 5 }] }, { category: "D", items: [{ name: "Dice", price: 5 }, { name: "Doll", price: 10 }] }]] } };

const result = input.data.products.reduce((res, arr) => {
  arr.forEach( o => res = res.concat(o.items));
  return res;
},[]);
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 4 :(得分:0)

您可以通过检查items属性或返回简化属性的结果来使用递归方法。此方法适用于任何深度,最后具有预期的items属性。

&#13;
&#13;
function flat(object) {
    return object.items || Object.keys(object).reduce(function (r, k) {
        return r.concat(flat(object[k]));
    }, []);
}

var object = { data: { products: [[{ category: "A", items: [{ name: "Aloe", price: 10 }, { name: "Apples", price: 5 }] }, { category: "B", items: [{ name: "Bread", price: 5 }] }], [{ category: "C", items: [{ name: "Candy", price: 5 }, { name: "Crayon", price: 5 }] }, { category: "D", items: [{ name: "Dice", price: 5 }, { name: "Doll", price: 10 }] }]] } }

console.log(flat(object));
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;