简体   繁体   English

Javascript group.json 键值进入列表

[英]Javascript group .json key value into list

I have the following json file structure that includes years from 2008 to 2020, along with other keys such as location, name, etc.:我有以下 json 文件结构,其中包括从 2008 年到 2020 年的年份,以及位置、名称等其他键:

{"2008": 50, "2009": 60, "2010": 70, "2011": 80, etc...}

I am trying to group the years into another key and adding it to the original array:我正在尝试将年份分组到另一个键中并将其添加到原始数组中:

{metric:
    [{"year": 2008, "perc": 50},
     {"year": 2009, "perc": 60},
     {"year": 2010, "perc": 70},
     {"year": 2011, "perc": 80}],
 "2008": 50, 
 "2009": 60,
 "2010": 70,
 "2011": 80,
 etc...
}

I think I need to create a range between 2008 to 2020, and if I detect a key that's within that range, I add to the metrics group and add that to the array?我想我需要在 2008 年到 2020 年之间创建一个范围,如果我检测到该范围内的键,我会添加到metrics组并将其添加到数组中吗?

What you have is an object, not an array.您拥有的是 object,而不是数组。 You can use a for-in loop or a for-of loop on Object.entries or similar to loop through the object, and then it's a matter of converting the year to a number and comparing it to your range and if it's in range, adding it to the metric array:您可以在Object.entries或类似内容上使用for-in循环或for-of循环来循环 object,然后将年份转换为数字并将其与您的范围进行比较,如果它在范围内,将其添加到metric数组:

 const data = {"2008": 50, "2009": 60, "2010": 70, "2011": 80, "2001": 20, "2002:": 30}; // Loop through the object for (const [year, perc] of Object.entries(data)) { // Get the year as a number const yearValue = +year; // See note below if (yearValue >= 2008 && yearValue <= 2020) { // It's in range, get or create the `metric` array const metric = data.metric?? (data.metric = []); // Add to it metric.push({year, perc}); } } console.log(data);

(I added a couple of out-of-range years there to show the range working.) (我在那里添加了几个超出范围的年份来显示范围工作。)

Using unary + to convert to number is just one of your options, I go through the full range of them in my answer here .使用一元+转换为数字只是您的选择之一,我在我的答案中通过所有范围go

you need to loop though the object and create a new one您需要遍历 object 并创建一个新的

const group => obj {
    // create init object
    let output = {
        metric: []
    }

    // start loop
    for (const key in obj) {

        // check if object contains property
        if (Object.hasOwnProperty.call(obj, key)) {

            // check if key matches range and assign to metric if not
            if (!(/20(0[8-9]|1[0-9]|20)/gm).test(key)) output.metric.push({
                'year': key,
                'perc': obj[key]
            });
                
            //assign value if matches between 2008 to 2020
            else output[key] = obj[key]
        }
    }

    // return new object
    return output;
}

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

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