Giả sử sau đây là mảng của chúng tôi -
var details = [
{
studentName: "John",
studentMarks: [78, 98]
},
{
studentName: "David",
studentMarks: [87, 87]
},
{
studentName: "Bob",
studentMarks: [48, 58]
},
{
studentName: "Sam",
studentMarks: [98, 98]
},
] Chúng tôi cần xóa giá trị thuộc tính trùng lặp, tức là 87 đang lặp lại ở trên. Chúng tôi cần xóa nó.
Đối với điều này, hãy sử dụng khái niệm map ().
Ví dụ
Sau đây là mã -
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); Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js.
Đây, tên tệp của tôi là demo292.js.
Đầu ra
Điều này sẽ tạo ra kết quả sau trên bảng điều khiển -
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 }
]