基于密钥
问题描述:
对象的JavaScript的数组删除重复我有一个对象如下所示基于密钥
var fileList = [
{
identifier: "auto-1",
file: "mp.mp3"
},
{
identifier: "auto-2",
file: "ss.mp3"
},
{
identifier: "auto-3",
file: "mj.mp3"
},
{
identifier: "type1",
file: "ss.mp3"
},
{
identifier: "type2",
file: "sc.mp3"
},
{
identifier: "tyep3",
file: "mj.mp3"
}
]
我试图删除数组元素。如果identifier
包含文本auto
,我想删除元素,如果该对象的file
匹配的file
包含在对象中的标识符为type1
或type2
或type3
。标识符将是唯一的。
预期输出:
[
{
identifier: "auto-1",
file: "mp.mp3"
},
{
identifier: "type1",
file: "ss.mp3"
},
{
identifier: "type2",
file: "sc.mp3"
},
{
identifier: "tyep3",
file: "mj.mp3"
}
]
我曾尝试下面的代码片段,但由消除标识符type1
,type2
...等物体得到的唯一值。
_.uniq(fileList ,function(item){ return item.file + item.identifier; })
答
从我理解的那个小。 你可以用减少这一
检查代码片段
var fileList = [{
identifier: "auto-1",
file: "mp.mp3"
},
{
identifier: "auto-2",
file: "ss.mp3"
},
{
identifier: "auto-3",
file: "mj.mp3"
},
{
identifier: "type1",
file: "ss.mp3"
},
{
identifier: "type2",
file: "squirrel-chatter.mp3"
},
{
identifier: "type3",
file: "mj.mp3"
}
]
var fileList2 = [{
identifier: "auto-1",
file: "mp.mp3"
}, {
identifier: "type1",
file: "mp.mp3"
}]
var result;
result = fileList2.reduce(function callback(result, key, index, keysArray) {
debugger;
let indx = result.findIndex((item) => item.file === key.file)
if (indx > -1) {
result[indx].identifier = (key.identifier.includes("type")) ? key.identifier : result[indx].identifier
} else {
result.push(key)
}
return result
}, [])
console.log(result)
希望它可以帮助
答
我不太了解您的唯一标准:您的解释和预期产出似乎有冲突。
但是至少可以尝试接受迭代函数的_.uniqBy
。 https://lodash.com/docs/4.17.4#uniqBy
_.uniq
不,这可能是你的问题。
你在看不清楚的问题,请重新制定。我不明白你需要什么。 –
请清楚说明你正在寻找的是什么 – Geeky
@NelsonTeixeira你可以请让我知道你到底在找什么直线前进,这里我指定了输入对象和输出对象 – Sri