假设以下是我们的数组-
var details = [ { studentName: "John", studentMarks: [78, 98] }, { studentName: "David", studentMarks: [87, 87] }, { studentName: "Bob", studentMarks: [48, 58] }, { studentName: "Sam", studentMarks: [98, 98] }, ]
我们需要删除重复的属性值,即上面重复了87。我们需要将其删除。
为此,请使用的概念map()
。
以下是代码-
var details = [ { studentName: "John", studentMarks: [78, 98] }, { studentName: "David", studentMarks: [87, 87] }, { studentName: "Bob", studentMarks: [48, 58] }, { studentName: "Sam", studentMarks: [98, 98] }, ] details.map(tempObj => { if (typeof (tempObj.studentMarks) == 'object') { tempObj.studentMarks = [... new Set(tempObj.studentMarks)] if (tempObj.studentMarks.length == 1) { tempObj.studentMarks = tempObj.studentMarks[0] } } }); console.log(details);
要运行上述程序,您需要使用以下命令-
node fileName.js.
在这里,我的文件名为demo292.js。
输出结果
这将在控制台上产生以下输出-
PS C:\Users\Amit\javascript-code> node demo292.js [ { studentName: 'John', studentMarks: [ 78, 98 ] }, { studentName: 'David', studentMarks: 87 }, { studentName: 'Bob', studentMarks: [ 48, 58 ] }, { studentName: 'Sam', studentMarks: 98 } ]