首页 > 解决方案 > 如何将json值过滤到数组

问题描述

我有一个这样的json文件

let myfile = [
    {"name":"John","eid":664,"socialid":399,"testid":799},
    {"name":"Sam","testid":249,"eid":64,"socialid":80},
    {"name":"Albert","eid":422,"testid":20,"socialid":10},
    {"name":"Michel","eid":497,"testid":15,"socialid":60}]

从上面的 json 中,我想通过它的键名过滤所有值并将其推送到数组中。预期输出是:

"name": ["John", "Sam", "Albert", "Michel"],
"eid": [664, 64, 422, 497],
"testid": [799, 249, 20, 15],
"socialid": [399, 80, 10, 60]

如何做到这一点?

我试过这样

let arr3 = [];
$.each( myfile, function( key, value ) {
  if(this.hasOwnProperty('name'))
  {
    console.log("is there")
    arr3.push(value);
  }
});
console.log(arr3);

它没有按预期工作。

标签: javascriptjqueryjsonobject

解决方案


您可以将数组简化为一个对象:

let myfile = [
    { name: 'John', eid: 664, socialid: 399, testid: 799 },
    { name: 'Sam', testid: 249, eid: 64, socialid: 80 },
    { name: 'Albert', eid: 422, testid: 20, socialid: 10 },
    { name: 'Michel', eid: 497, testid: 15, socialid: 60 },
];

console.log(
    myfile.reduce(
        (result, item) =>
            Object.entries(item).reduce((result, [key, value]) => {
                result[key] = result[key] || [];
                result[key].push(value);
                return result;
            }, result),
        {},
    ),
);


推荐阅读