javascript - 如何将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);
它没有按预期工作。
解决方案
您可以将数组简化为一个对象:
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),
{},
),
);
推荐阅读
- azure-cosmosdb - Azure Cosmos Db .NET v3 -“输入名称‘null’无效。确保提供少于‘1024’字符的唯一非空字符串
- javascript - 努克特. 是否可以为 _nuxt 文件夹中生成的 js 文件设置自定义路径?
- python - 通过 Airflow 提取电子邮件内容
- python - 如何通过单个“单击”从列表框中删除焦点和选择?
- loops - [lua] 向我解释这段代码是如何工作的(嵌套循环)
- linux - ARM 中的页面演练
- regex - 正则表达式 - 如果有任何重复的小写字母,则匹配
- python - 如何序列化我的模型以获得所需的输出
- mysql - 锁 FOR UPDATE 是否允许 MySQL 中另一个连接的简单 SELECT 语句
- r - R - contour.default(x, y, z) 中的错误:预期增加“x”和“y”值