我有以下数组:
var tst =
[
{"topicId":1,"subTopicId":1,"topicName":"a","subTopicName":"w"},
{"topicId":1,"subTopicId":2,"topicName":"b","subTopicName":"x"},
{"topicId":1,"subTopicId":3,"topicName":"c","subTopicName":"y"},
{"topicId":2,"subTopicId":4,"topicName":"c","subTopicName":"z"}
]
有没有一种简单的方法可以将其映射到topicId>这种类型的数组id和topicName>名:
var t =
[
{"id":1,"name":"a"},
{"id":2,"name":"c"}
]
我正在使用现代浏览器,如果有帮助,我也有_lodash。请注意,tst数组中将有大约100行,因此我不需要非常优化的解决方案。简单易维护的解决方案更为重要。
答案 0 :(得分:33)
最近
var tst = [
{"topicId":1,"subTopicId":1,"topicName":"a","subTopicName1":"w"},
{"topicId":2,"subTopicId":2,"topicName":"b","subTopicName2":"x"},
{"topicId":3,"subTopicId":3,"topicName":"c","subTopicName3":"y"},
{"topicId":1,"subTopicId":4,"topicName":"c","subTopicName4":"z"}
];
var result = _.map(_.uniqBy(tst, 'topicId'), function (item) {
return {
id: item.topicId,
name: item.topicName
};
});
console.log(result);
<强> LEGACY 强>
http://lodash.com/docs#uniq是一个好的开始
_.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
您的代码看起来像是为了获取id
唯一的主题var t = _.uniq(tst, 'topicId');
修改强>
我做了一个jsfiddle
<强>更新强>
删除了不必要的名称唯一性
答案 1 :(得分:2)
我是那些使用原生函数的人之一:)
var results = tst.reduce(function(res,topic){
var exists = res.some(function(t){ return (t.id === topic.topicId && t.name === topic.topicName);});
if (!exists){
res.push({"id": topic.topicId, "name": topic.topicName});
}
return res; },[]);
Lodash版本
我不是使用lodash的专家,可能我会尝试这样的事情:
var results = _.reduce(tst, function(res, topic){
var exists = _.findIndex(res, function(t){
return (t.id === topic.topicId && t.name === topic.topicName);
});
if (exists === -1){
res.push({"id": topic.topicId, "name": topic.topicName});
}
return res;
},[]);
答案 2 :(得分:-1)
Array.prototype.find()
find()方法返回数组中第一个满足提供的测试函数的元素的值。否则返回undefined。
let tst = [
{"topicId":1,"subTopicId":1,"topicName":"a","subTopicName":"w"},
{"topicId":1,"subTopicId":2,"topicName":"b","subTopicName":"x"},
{"topicId":1,"subTopicId":3,"topicName":"c","subTopicName":"y"},
{"topicId":2,"subTopicId":4,"topicName":"c","subTopicName":"z"},
];
let t = [];
tst.forEach(obj => {
// Check if the id already exists in the array 't'
if (!t.find((self) => self.id === obj.topicId)) {
// If not, pushes obj to t
t.push({
id: obj.topicId,
name: obj.topicName
});
}
});
console.log(t);
&#13;
您还可以比较多个属性:
let tst = [
{"topicId":1,"subTopicId":1,"topicName":"a","subTopicName":"w"},
{"topicId":1,"subTopicId":2,"topicName":"b","subTopicName":"x"},
{"topicId":1,"subTopicId":3,"topicName":"c","subTopicName":"y"},
{"topicId":2,"subTopicId":4,"topicName":"c","subTopicName":"z"},
];
let t = [];
tst.forEach(obj => {
// Check if the 'id' and 'subId' already exist in t
if (!t.find((self) => self.id === obj.topicId && self.subId === obj.subTopicId)) {
// If not, pushes obj to t
t.push({
id: obj.topicId,
subId: obj.subTopicId,
name: obj.topicName
});
}
});
console.log(t);
&#13;