简体   繁体   English

如何使用未知的键和值遍历对象

[英]How to loop over object with unknown keys and values

I get a JSON response of shoe sizes from an API endpoint that looks like this: 我从API端点获得鞋号的JSON响应,如下所示:

data: [{
    0: {
        system: "US",
        sizes: {
            7: {B: 3, C: 6, D: 1, E: 1}
            7.5: {A: 6, B: 7, C: 14, D: 11, E: 2}
            8: {2E: 1, A: 5, B: 32, C: 38, D: 23, …}
            8.5: {2E: 2, A: 9, B: 56, C: 79, D: 61, …}
            9: {2A: 5, 2E: 4, A: 17, B: 92, C: 143, …}
            9.5: {2A: 3, 2E: 3, A: 26, B: 132, C: 194, …}
            10: {2A: 5, 2E: 3, 3A: 1, A: 53, B: 159, …}
        }
    }
}]

The data shows eg that US size 7 has four different kinds of shapes (B, C, D, E) where 3 people have foots of shape B. In total, 11 people has size 7. The list can contain sizes in US, EU or different systems, and key of shapes can be AZ or basically anything else. 数据显示,例如,美国7号尺码有四种不同的形状(B,C,D,E),其中3人的脚型为B。总共11人的尺码为7。此列表可以包含美国,欧盟的尺码或不同的系统,形状的关键可以是AZ或基本上其他任何形状。

I want to loop over sizes and create a diagram of how many people that has a certain size, and how many has a certain shape of that size. 我想遍历sizes并创建一个图表,以显示有多少人具有一定的大小,以及多少人具有该大小的某种形状。

What would be the best way to loop over an object like this to get the value of every shape? 在这样的对象上循环以获取每个形状的值的最佳方法是什么? I would expect it to be an array of sizes. 我希望它是一系列尺寸。

ES6 or ES7 is fine but I would prefer to do it without jQuery. ES6或ES7很好,但我更喜欢不使用jQuery。

EDIT: Let me be more clear. 编辑:让我更清楚。 First of all I have considered improving data structure but unfortunately that's not an option. 首先,我已经考虑过改善数据结构,但是不幸的是这不是一个选择。

I have tried Object.keys(sizes) which returns an array of the keys. 我已经尝试过Object.keys(sizes)返回键数组。 Sure that's one step forward. 当然,这是前进的一步。 But I would like to call a function that returns an object with the keys and its values. 但是我想调用一个函数,该函数返回带有键及其值的对象。 In my mind, that return value should be something like this: 在我看来,该返回值应该是这样的:

sizes: [
    {
        size: 7,
        total: 11
        shapes: [
            {name: 'B', value: 3},
            {name: 'C', value: 6},
            {name: 'D', value: 1},
            {name: 'E', value: 1}
        ]
    },{...},{...}
]

Does that makes sense? 这有意义吗? Of course, length is not absolutely necessary to include in the object. 当然,长度不是绝对必需包含在对象中。

You can extract all of the keys of an object into an array and simply iterate over that array. 您可以将对象的所有键提取到数组中,然后简单地对该数组进行迭代。

 var obj = { 'key1': 'val1', 'key2': 'val2' } var keys = Object.keys(obj); // ['key1', 'key2'] keys.forEach( function(key) { var values = obj[key] console.log(values) // do stuff with "values" }) 


Reference - 参考-

You can use array#map , Object.keys() and array#reduce . 您可以使用array#mapObject.keys()array#reduce

 const data = [{system:'US',sizes:{7:{B:3,C:6,D:1,E:1,}, 7.5: { A: 6, B: 7, C: 14, D: 11, E: 2, }, 8: { '2E': 1, A: 5, B: 32, C: 38, D: 23, }, 8.5: { '2E': 2, A: 9, B: 56, C: 79, D: 61, }, 9: { '2A': 5, '2E': 4, A: 17, B: 92, C: 143, }, 9.5: { '2A': 3, '2E': 3, A: 26, B: 132, C: 194, }, 10: { '2A': 5, '2E': 3, '3A': 1, A: 53, B: 159, }, }, }, ]; var result = data.map((obj) => { return Object.keys(obj.sizes).reduce((arr,k) => { let res = Object.keys(obj.sizes[k]).reduce((r, k1) => { r['size'] = k; r.shapes.push({name: k1, value: obj.sizes[k][k1]}); r.total += obj.sizes[k][k1]; return r; },{shapes:[],total:0}); arr.push(res); return arr; },[]); }) console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

Use Object.keys() and .reduce() to sum the values of the keys. 使用Object.keys().reduce()对键的值求和。

NOTE : I had to clean your data, and remove a level to simplify the example. 注意 :我必须清理您的数据,并删除一个级别以简化示例。 You'll need to adapt it to your real data. 您需要根据实际数据进行调整。

 const data = [ { system: 'US', sizes: { 7: { B: 3, C: 6, D: 1, E: 1, }, 7.5: { A: 6, B: 7, C: 14, D: 11, E: 2, }, 8: { '2E': 1, A: 5, B: 32, C: 38, D: 23, }, 8.5: { '2E': 2, A: 9, B: 56, C: 79, D: 61, }, 9: { '2A': 5, '2E': 4, A: 17, B: 92, C: 143, }, 9.5: { '2A': 3, '2E': 3, A: 26, B: 132, C: 194, }, 10: { '2A': 5, '2E': 3, '3A': 1, A: 53, B: 159, }, }, }, ]; const { // We use destructuration to make a copy sizes = {} // We assign a default value in case sizes is undefined } = data[0]; const sumOfSizes = {}; // Future object we will fill Object.keys(sizes).forEach((sizeIndex) => { // We get the keys of the object, and loop over it. const size = sizes[sizeIndex]; // For clarity, I assigned the needed value to a var. const sumOfShapes = Object.keys(size).reduce((prevSum, shapeIndex) => { // We get the sub-keys of the object and sum the values of them. const shapeValue = size[shapeIndex]; return prevSum + shapeValue; }, 0); sumOfSizes[sizeIndex] = sumOfShapes; // We assign the sum of shapes to the current shoe size. }); console.log(sumOfSizes); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM