我有一个结构如下的对象 const data = [ { academicYearId: 1, classLevelId: 1, subjectId: 1, ...}, { academicYearId: 1, classLevelId: 1, subjectId: 2, ...}, { academicYearId: 1, classLevelId: 1, subjectId: 3, ...}, ,,, ]我需要创建一个将返回唯一列的函数,例如 const uniqueColumns = ( val, columns)=> { // } const val = [ { id: 1, name: 'n1', val: 1 }, { id: 1, name: 'n1', val: 2 }, { id: 2, name: 'n2', val: 1 }, { id: 3, name: 'n2', val: 2 } ] let result = uniqueColumns(val) console.log(val) /** * Expected * [{ id: 1, name: 'n1'}, { id: 2, name: 'n2'}, { id: 3, name: 'n2'}] */}我试图查看如何从 JavaScript 中的对象数组中获取不同的值?我已经设法想出了下面的 const uniqueColumns = (val, columns) => ([...new Set( val.map(item => columns.reduce((prev, next) => ({[next]: item[next], ...prev}), {}) ).map(item => JSON.stringify(item))) ].map(item => JSON.parse(item))) const val = [ { id: 1, name: 'n1', val: 1 }, { id: 1, name: 'n1', val: 2 }, { id: 2, name: 'n2', val: 1 }, { id: 3, name: 'n2', val: 2 } ] const result = uniqueColumns(val, ['id', 'name']) console.log(result)我想问的是是否有更好的方法而不是必须将对象转换为字符串然后再转换回对象来实现这一点
1 回答
慕雪6442864
TA贡献1812条经验 获得超5个赞
您可以使用数组 reduce 方法。
const val = [
{ id: 1, name: "n1", val: 1 },
{ id: 1, name: "n1", val: 2 },
{ id: 2, name: "n2", val: 1 },
{ id: 3, name: "n2", val: 2 },
];
const uniqueColumns = (val, columns) => {
let ret = val.reduce((p, c) => {
let obj = {};
columns.forEach((x) => (obj[x] = c[x]));
let key = Object.values(obj);
if (!p[key]) p[key] = obj;
return p;
}, {});
return Object.values(ret);
};
const result = uniqueColumns(val, ["id", "name"]);
console.log(result);
添加回答
举报
0/150
提交
取消