【问题标题】:Remove duplicates from a json list javascript从 json 列表 javascript 中删除重复项
【发布时间】:2021-07-24 04:24:42
【问题描述】:

晚上好, 我有这个来自 mongoDB 的列表,我想删除“标题”中包含的国家/地区的重复项,以将它们插入选择框中。

{
    "_id": {
        "$oid": "60885f86f642f81910ca8715"
    },
    "title": "france",
    "phase": "budget",
    "amount": 45555,
    "month": 1,
    "year": 2020,
    "availibleYears": "2020"
}

{
    "_id": {
        "$oid": "60885f86f642f81910ca8716"
    },
    "title": "france",
    "phase": "budget",
    "amount": 7777,
    "month": 2,
    "year": 2020,
    "availibleYears": "2020"
}
{
    "_id": {
        "$oid": "60885f86f642f81910ca8717"
    },
    "title": "france",
    "phase": "budget",
    "amount": 8777,
    "month": 1,
    "year": 2019,
    "availibleYears": "2019"
}

{
    "_id": {
        "$oid": "60885f86f642f81910ca8719"
    },
    "title": "germany",
    "phase": "budget",
    "amount": 6767,
    "month": 1,
    "year": 2020,
    "availibleYears": "2020"
}

到目前为止,我发现了这个:

getUnique(arr, comp){
        const unique = arr
        //store the comparison values in array
        .map(e => e[comp])
        //store the keys of the unique objects
        .map((e, i, final) => final.indexOf(e) === i && i)
        //eliminate the dead keys (duplicate) & store unique objects
        .filter(e => arr[e])
        .map(e => arr[e])
        return unique
    }

我的选择是:

<div className="choose-country">
                    Select {" "}
                    <select>
                       {uniqueCountry.map(country => (
                                <option key={country._id}
                                        value={country.title}>
                                        {country.title}
                                </option>
                       ))}
                    </select>
 </div>

我只有一个国家返回了 getUnique 函数,因为我使用的代码是用于我相信的数组? 我该怎么做 ? 希望它足够清楚,并提前感谢您!

【问题讨论】:

  • 对于初学者来说,这似乎完全是关于 JavaScript,而不是 Java。

标签: javascript json reactjs mongodb duplicates


【解决方案1】:

我希望我明白你在问什么。 以下是如何按标题选择唯一元素:

 getUnique(arr){
   return arr.reduce((accumulator, el) =>{
    if(!accumulator.some(existing => el.title === existing.title)){
      accumulator.push(el); 
    }
    return accumulator;
   },[]);
}

【讨论】:

    猜你喜欢
    • 2014-09-30
    • 2011-01-13
    • 2021-04-02
    • 2016-01-28
    相关资源
    最近更新 更多