天真的方法总结了一系列对象?

发布于 2025-02-12 08:19:00 字数 110 浏览 1 评论 0原文

我面临着一个挑战,需要通过对象键总结一系列对象。我找到了一个解决方案,但是我无法摆脱这种感觉,我的方法很幼稚:

const objArr = [
    { id: 1, val: "
              

I faced a challenge where I needed to summarize an array of objects by the object's keys. I found a solution, but I can't shake off the feeling, that my approach is pretty naive:

const objArr = [
    { id: 1, val: "????" },
    { id: 1, val: "????" },
    { id: 1, val: "????" },
    { id: 2, val: "????" },
    { id: 2, val: "????" },
    { id: 2, val: "????" },
];

let tempArr = [];
let uniqueIdArr = [];
let sortedArr = [];

objArr.forEach((obj) => {
    tempArr.push(obj.id);
    uniqueIdArr = [...new Set(tempArr)];
});

uniqueIdArr.forEach((uniqueId) => {
    let arr = [];
    objArr.forEach((obj) => {
        if (obj.id == uniqueId) {
            arr.push(obj.val);
        }
    });
    sortedArr.push({
        id: uniqueId,
        vals: arr,
    });
});

console.log(sortedArr);
// Output: [{ id: 1, vals: [ '????', '????', '????' ] }, { id: 2, vals: [ '????', '????', '????' ] }]

Maybe there is something I don't know about JavaScript's array methods yet? Is this approach totally wrong? Is there another way, so that I could reduce the code and make it more elegant?

So many questions...

Any hint or explanation would be much appreciated. ????

Thanks in advance

J.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

十级心震 2025-02-19 08:19:00

您可以使用array.prototype.reduce使您的代码位短:

const objArr = [
{ id: 1, val: "

you can use Array.prototype.reduce to make your code bit shorter:

const objArr = [
    { id: 1, val: "????" },
    { id: 1, val: "????" },
    { id: 1, val: "????" },
    { id: 2, val: "????" },
    { id: 2, val: "????" },
    { id: 2, val: "????" },
];

let result = objArr.reduce((acc,e) => {
    let idx = acc.findIndex(s => s.id === e.id)
    if(idx > -1){
        acc[idx].vals.push(e.val)
    }
    else{
        acc.push({id:e.id,vals:[e.val]})
    }
    return acc
},[])


console.log(result)

我不是你的备胎 2025-02-19 08:19:00

您的想法是好的和明确的,但远非最佳。

const objArr = [
{ id: 1, val: "

Your ideas are good and explicit, but far from being optimal.

const objArr = [
    { id: 1, val: "????" },
    { id: 1, val: "????" },
    { id: 1, val: "????" },
    { id: 2, val: "????" },
    { id: 2, val: "????" },
    { id: 2, val: "????" },
];
const idValMap = new Map();

objArr.forEach(o=>{
   let vals = idValMap.get(o.id);
   if(!vals){
       vals = [];
       idValMap.set(o.id,vals);
   }
   vals.push(o.val);
});

console.log(Array.from(idValMap.entries()));

You can do most of it in just one loop. Take the key, check if you saw it already, if not initialize. That's it

一紙繁鸢 2025-02-19 08:19:00

该解决方案可能不是好多了,但它确实使用较少的代码:

const objArr = [
{ id: 1, val: "

This solution probably isn't much better but it is does use less code:

const objArr = [
    { id: 1, val: "????" },
    { id: 1, val: "????" },
    { id: 1, val: "????" },
    { id: 2, val: "????" },
    { id: 2, val: "????" },
    { id: 2, val: "????" },
];

let sortedArr = [];

objArr.forEach((item) => {
    const exists = sortedArr.filter(i => i.id === item.id).length; // Check to see if we've already added an item with this ID
    if (!exists) {
        const matches = objArr.filter(i => i.id == item.id); // get all items with this ID

        sortedArr.push({
            id: item.id,
            vals: matches.map(m => m.val) // We only care about the val property
        });
    }
});

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for informationa bout .map() and .filter() respectively

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文