简体   繁体   English

将嵌套的 JSON 值推送到数组

[英]Push nested JSON values to array

I have a JSON array of the following type:我有一个以下类型的 JSON 数组:

"team": [ 
          {
            "paid": {
                "refugee": 2018,
                  "local": 29000, 
                  "international": 12000
            }
        },
        {
            "unpaid": {
                "refugee": 2019,
                "local": 39000, 
                "international": 19000
            }
        }
    ]

I would like to push the values of matching keys into an array, so that I end up with the following new arrays:我想将匹配键的值推送到一个数组中,以便我最终得到以下新数组:

var refugees = [2018, 2019]
var local = [29000, 39000]
var international = [12000, 19000]

and so on..等等..

What would be a simple method of doing this?这样做的简单方法是什么? I have succesfully used jQuery in the past for this but need a Javascript only solution:我过去曾为此成功使用过 jQuery,但只需要一个 Javascript 解决方案:

$.each(team, function (i, v) {
                var teams = v;
                console.log(teams);
                $.each(v, function (i, v) {
                    refugees.push(v.refugee);
                    local.push(v.local);
                    international.push(v.international);
                });
            });

Try this 尝试这个

 var a={"team" : [ { "paid": { "refugee": 2018, "local": 29000, "international": 12000 } }, { "unpaid": { "refugee": 2019, "local": 39000, "international": 19000 } } ]} var refugee=[]; var local=[]; var international=[]; a.team.map((e)=>{ if(e.paid) { refugee.push(e.paid.refugee); local.push(e.paid.local); international.push(e.paid.international) } else { refugee.push(e.unpaid.refugee); local.push(e.unpaid.local); international.push(e.unpaid.international) } }) console.log(local) console.log(international) console.log(refugee) 

You can use reduce. 您可以使用reduce。

So here the idea is we are taking a the keys and mapping it to output object. 因此,这里的想法是我们使用一个键并将其映射到输出对象。 we keep checking if the key is already their in output object we push the value to that particular key and if not we add a new property with value. 我们一直检查键是否已经在输出对象中,我们将值推入该特定键,如果不是,则添加一个带有value的新属性。

 let obj = {"team":[{"paid":{"refugee":2018,"local":29000,"international":12000}},{"unpaid":{"refugee":2019,"local":39000,"international":19000}}]} let op = obj.team.reduce((output,current)=>{ let temp = Object.values(current)[0] let values = Object.keys(temp) values.forEach(ele=>{ if(output[ele]){ output[ele].push(temp[ele]) } else { output[ele] = [temp[ele]] } }) return output; }, {}) console.log(op) 

Something like this would work if you wanted a few one-liners: 如果您想要一些单线,类似这样的事情将起作用:

let local = team.reduce((acc, item) => acc.concat(Object.values(item).map(val => val.local)), []);

let refugee = team.reduce((acc, item) => acc.concat(Object.values(item).map(val => val.refugee)), []);

In it's simplest form, you can just get the right path to you object property and set it. 以最简单的形式,您可以获取对象属性的正确路径并进行设置。 More than likely, it's not going to be that straight forward in your use case. 在您的用例中,很有可能不会那么简单。 You will more than likely need to use some sort of method to find the object you're after and then set it form there. 您极有可能需要使用某种方法来找到要寻找的对象,然后在此处设置它的形式。 .find , .filter and .includes are excellent tools for searching arrays for content. .find.filter.includes是用于在数组中搜索内容的出色工具。

One thing to also note here is that the current values of refugee and local are not in array format . 这里还需要注意的一件事是, refugeelocal的当前价值不是数组格式 With that being said .push is not an option. 话虽如此, .push并不是一个选择。 You first need to set the property value to an array, then you may use Array.push 您首先需要将属性值设置为数组,然后可以使用Array.push

 const json = {"team": [ { "paid": { "refugee": 2018, "local": 29000, "international": 12000 } }, { "unpaid": { "refugee": 2019, "local": 39000, "international": 19000 } } ]}; json.team[0].paid.refugee = [2018, 2019]; json.team[0].paid.local = [2900, 3900]; console.log(json); 

Use Array#reduce, Object#values, Object#entries, spread syntax, destructuring and Map 使用Array#reduce,Object#values,Object#entries,扩展语法,解构和Map

 const data={"team":[{"paid":{"refugee":2018,"local":29000,"international":12000}},{"unpaid":{"refugee":2019,"local":39000,"international":19000}}]} const res = data.team.reduce((a,c)=>{ Object.values(c) .map(Object.entries) .flat() .forEach(([k,v])=>{ const arr = a.get(k) || []; arr.push(v) a.set(k, arr); }) return a; }, new Map()) //get all console.log([...res.values()]); //get by type console.log(res.get('refugee')); console.log(res.get('local')); console.log(res.get('international')); 

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

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