Javascript复制无重复对象数据从数组中具有相同的属性

Javascript复制无重复对象数据从数组中具有相同的属性,javascript,Javascript,我有一个arry,它有100个对象,并且它有相同的属性code Data = [ {yera:"2019", name:"saif", topic:"oil"}, {yera:"2018", name:"abc", topic: "oil"}, {yera:"2018", name:"jorj", topic:"energy"}, {yera:"2017", name:"tom", topic:"gas"}, {yera:"2016",name:"saif",topic:"elect

我有一个arry,它有100个对象,并且它有相同的属性
code

Data = [ 

{yera:"2019", name:"saif", topic:"oil"},

{yera:"2018", name:"abc", topic: "oil"},

{yera:"2018", name:"jorj", topic:"energy"},

{yera:"2017", name:"tom", topic:"gas"},

{yera:"2016",name:"saif",topic:"electricity "},

{yera:"2014", name:"gour",topic:"oil"},

假设您希望根据对象的键从对象数组中删除重复项,下面的代码将实现这一点

var data = [

    {yera:"2019", name:"saif", topic:"oil"},

    {yera:"2018", name:"abc", topic: "oil"},

    {yera:"2018", name:"jorj", topic:"energy"},

    {yera:"2017", name:"tom", topic:"gas"},

    {yera:"2016",name:"saif",topic:"electricity "},

    {yera:"2014", name:"gour",topic:"oil"}
]


function getUniqueData(originalData, keyToCheckForUniqueness) {
    var store = {};
    var output = [];
    originalData.forEach(function (ob) {

        var val = ob[keyToCheckForUniqueness];

        if (!store[val]) {
            store[val] = [ob]; 
        } else {
            store[val].push(ob);
        }

    });
    // at this point your store contains all the repeating data based on that property value
    // console.log(store);

    // now emit single values from that store; 
    // this logic can be based on any criterion, I chose the first element of the array - it may change depending on the order of values in input
    Object.keys(store).forEach(function (key) {
        var uniqueValArray = store[key];
        var uniqueVal = uniqueValArray[0]; // take the first entry
        output.push(uniqueVal);
    });
    return output;
}

getUniqueData(data, "topic");

这将实现我认为你想要的结果。一句忠告——当你向人们寻求帮助时,不要让他们思考。其次,试着为自己编写逻辑。张贴你的非工作解决方案,并询问你在哪里犯了错误,而不是询问。鉴于您的代表,欢迎来到SO。希望您有一个很好的学习体验。

假设您希望对象的给定属性具有唯一的值,您可以映射该值并采取适当的方法来获取唯一的值

函数getUnique(数组,键){
返回Array.from(新集合(Array.map(({[key]:v})=>v));
}
var数组=[{年份:“2019”,名称:“grace”,主题:“石油”},{年份:“2018”,名称:“grace”,主题:“石油”},{年份:“2018”,名称:“jane”,主题:“能源”},{年份:“2017”,名称:“tom”,主题:“天然气”},{年份:“2016”,名称:“jane”,主题:“电力”},{年份:“2014”,名称:“gour”,主题:“石油”};
log(getUnique(数组,'year');
log(getUnique(数组,'name'));
log(getUnique(数组,'topic')

。作为控制台包装{max height:100%!important;top:0;}
请添加您喜欢做的事情,以及一些代码,可能。我想从新数组中的数据复制所有对象,新数组只在数据数组中存储唯一的对象一些重复的对象,即我想复制新数组中数据数组的主题属性,新数组应该存储唯一的主题值,如新数组=[“油”、“能源”、“气”、“电”],而不是新数组=[“油”、“油”、“油”,“能源”、“天然气”、“电力”]例如,从数据数组复制vtopic值并忽略如果主题值复制并从数据数组复制下一个主题值并存储新数组新数组是一个新数组,将存储复制值我们可以在angular 6i中使用此方法在angular 6中尝试此方法它不起作用抱歉,我不知道angular。