有什么方法可以解决此问题而无需将这两个数组连接起来以获得具有更高价值的对象?
要获取具有特定属性的对象,请分别在两个数组上使用reduce()的概念。您不需要串联。假设以下是带有学生姓名和学生标记的对象
var sectionAStudentDetails = [ {studentName: 'John', studentMarks: 78}, {studentName: 'David', studentMarks: 65}, {studentName: 'Bob', studentMarks: 98} ]; let sectionBStudentDetails = [ {studentName: 'John', studentMarks: 67}, {studentName: 'David', studentMarks: 89}, {studentName: 'Bob', studentMarks: 97} ];
以下是在两个代码上都实现reduce()并获取具有较高值(标记)的对象的代码-
示例
var sectionAStudentDetails = [ {studentName: 'John', studentMarks: 78}, {studentName: 'David', studentMarks: 65}, {studentName: 'Bob', studentMarks: 98} ]; let sectionBStudentDetails = [ {studentName: 'John', studentMarks: 67}, {studentName: 'David', studentMarks: 89}, {studentName: 'Bob', studentMarks: 97} ]; function concatTwoArraysWithoutConcatFunction(arrayValues, k) { const previousValue = arrayValues[k.studentName]; if (!previousValue || k.studentMarks >= previousValue.studentMarks) arrayValues[k.studentName] = k; return arrayValues; } const setionA = sectionAStudentDetails.reduce(concatTwoArraysWithoutConcatFunction, {}); const sectionB = sectionBStudentDetails.reduce(concatTwoArraysWithoutConcatFunction, setionA); console.log(Object.values(sectionB));
要运行上述程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo84.js。
输出结果
这将产生以下输出-
PS C:\Users\Amit\JavaScript-code> node demo84.js [ { studentName: 'John', studentMarks: 78 }, { studentName: 'David', studentMarks: 89 }, { studentName: 'Bob', studentMarks: 98 } ]