我有一个Javascript对象(大小不确定),其中的值是一个字符串数组。例如:
var obj = {
"article1": ["john locke", "sawyer", "john Locke"] ,
"article2": ["person3", "person4"]
}
我想进行转换,以便删除所有重复的字符串。
这意味着对于上面的示例,我有
var finalObj = {
"article1": ["john locke", "sawyer"], //"john Locke" was removed"
"article2": ["person3", "person4"]
}
它必须不区分大小写,即如果开头有“ john locke”,则应该删除john Locke。
如何实现?
答案 0 :(得分:2)
您可以使用for...in
和reduce
for ... in
遍历对象includes
属性中,如果不存在,则用当前值更新final
并将该键添加到includes
中属性为true
final
并将其分配给对象的键
let obj = {
"article1": ["john locke", "sawyer", "john Locke"],
"article2": ["person3", "person4"]
}
let removeDuplicate = (arr) => {
let output = arr.reduce((op, inp) => {
let key = inp.toLowerCase()
if (!op.includes[key]) {
op.final.push(inp)
op.includes[key] = true
}
return op
}, { includes: {}, final: [] })
return output.final
}
for (let key in obj) {
obj[key] = removeDuplicate(obj[key])
}
console.log(obj)
答案 1 :(得分:2)
因此,首先循环遍历键,而不是使用一组对数组进行重复数据删除。由于似乎大小写无关紧要,所以在将其用于集合之前,需要先降低数组的大小。
var obj = {
"article1": ["john locke", "sawyer", "john Locke"],
"article2": ["person3", "person4"]
}
var finalObj = Object.entries(obj).reduce((o, [key, arr]) => {
o[key] = [...new Set(arr.map(t => t.toLowerCase()))]
return o
}, {})
console.log(finalObj)
答案 2 :(得分:1)
您可以使用new Set()
,但是在此之前,您需要处理不敏感的情况,例如lock
Lock
。
const obj = {
"article1": ["john locke", "sawyer", "john Locke"],
"article2": ["person3", "person4"]
};
// this is for all the fields that are array ( will have unique elements )
for(let key in obj){
if(Array.isArray(obj[key])){
obj[key] = obj[key].map(el => el.toLowerCase());
obj[key] = [...new Set(obj[key])];
}
}
console.log(obj)
答案 3 :(得分:0)
这是示例代码:
Object.keys(obj)
.forEach(function (k) {
var dict = {};
obj[k].forEach(function (v, i) {
v = v.toLowerCase(); // make value lower case since "john locke"!="john Locke"
if (dict[v]) {
obj[k].splice(i, 1);
}
dict[v] = true;
});
});
请注意,此代码修改了对象obj
和内部数组。
答案 4 :(得分:0)
这将起作用-
Orange
答案 5 :(得分:0)
对于Obj中的每个attr: 1.将数组映射为小写值 2.过滤重复项
var obj = {
"article1": ["john locke", "sawyer", "john Locke"],
"article2": ["person3", "person4"]
}
var newObj = {}
for(let attr in obj) {
newObj[attr] = obj[attr].map(item => item.toLowerCase())
.filter((item, idx, arr) => arr.indexOf(item) === idx)
}
console.log(newObj);
答案 6 :(得分:0)
用于... in,set,map和Array.from:
var obj = {
"article1": ["john locke", "sawyer", "john Locke"] ,
"article2": ["person3", "person4"]
}
var newObj = {}
for (let k in obj){
newObj[k] = Array.from(new Set(obj[k].map((i) => i.toLowerCase())))
}
console.log(newObj)