Un-nesting JavaScript 中的对象数组?
若要取消嵌套对象数组,请使用 map() 的概念。我们假设对象数组如下所示 −
const studentDetails = [ { "studentId": 101, "studentName": "John", "subjectDetails": { "subjectName": "JavaScript" } }, { "studentId": 102, "studentName": "David", "subjectDetails": { "subjectName": "MongoDB" } } ];
我们需取消嵌套 subjectName 并显示结果。代码如下 −
实例
const studentDetails = [ { "studentId": 101, "studentName": "John", "subjectDetails": { "subjectName": "JavaScript" } }, { "studentId": 102, "studentName": "David", "subjectDetails": { "subjectName": "MongoDB" } } ]; const output = studentDetails.map(obj => ({ studentId: obj.studentId, studentName: obj.studentName, subjectName:obj.subjectDetails.subjectName })); console.log(output);
若要运行上面的程序,你需要使用以下命令 −
node fileName.js.
输出
此处,我的文件名是 demo92.js。这将产生以下输出 −
PS C:\Users\Amit\JavaScript-code> node demo92.js [ { studentId: 101, studentName: 'John', subjectName: 'JavaScript' }, { studentId: 102, studentName: 'David', subjectName: 'MongoDB' } ]
广告