dx15618816293
Colin听雨
采纳率50%
2021-03-01 22:20

求大佬帮忙解析json对象数组

现有数据:

var data = {"学生":["小红","小明","小白"],"班级":["1班","2班"],"性别":["nan","nv"]};

需要解析成

[
{"学生":"小红","班级":"1班"},
{"学生":"小明","班级":"1班"},
{"学生":"小白","班级":"1班"},
{"学生":"小红","班级":"2班"},
{"学生":"小明","班级":"2班"},
{"学生":"小白","班级":"2班"}
]

但是有额外要求,这个对象的key的数量不确定,value的值的数组长度也不确定

求个大佬贴个代码

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • jslang 天际的海浪 2月前
    var data = {"学生":["小红","小明","小白"],"班级":["1班","2班"],"性别":["nan","nv"]};
    var keys = ["学生","班级"]; //需要提取的key
    var arr = [{}];
    for (var i = 0; i < keys.length; i++) {
    	var t = [];
    	for (var k = 0; k < data[keys[i]].length; k++)
    		for (var j = 0; j < arr.length; j++)
    			t.push({...arr[j] ,[keys[i]]:data[keys[i]][k]});
    	arr = t;
    }
    console.log(arr);
    
    点赞 1 评论 复制链接分享
  • zhshchilss zhshchilss 2月前

    额外要求看不明白,只看data和解析后的数据,是所有学生匹配所有班
    let {students,classes} = data ;
    return students.flatMap(s=>return classes.map(c=>({student:s,class:c})))

    点赞 评论 复制链接分享

相关推荐