在 AngularJS 中,我有一个来自 JSON API 调用的数千条记录的对象。我需要从每个记录(“主题”)中创建一个仅包含一个特定键的新数组,从而仅生成一组唯一值。 foreach 循环是执行此操作的唯一方法吗?例如:
数据数组(arr):
{
"id": 1,
"number": 2,
"section": "xx",
"importance": "high",
"applicability": "General",
"text": "some text here",
"topic":
{
"id": 30,
"title": "Gender and Diversity"
}
},
{
"id": 2,
"number": 2.1,
"section": "xx",
"importance": "high",
"applicability": "General",
"text": "some text here",
"topic":
{
"id": 31,
"title": "Health and Safety"
}
}, ...
我想要一个仅包含数千条记录中的主题的数组,如下所示:
"topic":
{
"id": 30,
"title": "Gender and Diversity"
},
"topic":
{
"id": 31,
"title": "Health and Safety"
},..
是否有比我目前拥有的更好(更快)的方法来创建此列表,即带有 if 语句的 foreach 循环,后跟唯一值的过滤器?:
var topics = function (arr) {
var topics = [];
angular.forEach(arr.data, function (ts) {
angular.forEach(ts.topic, function (t) {
if (t.title) {
this.push(t);
}
}, topics);
});
// Filter the unique values
var elementId = [];
var uniqueTopics = topics.filter(el => {
if (elementId.indexOf(el.id) === -1) {
// If not present in array, then add it
elementId.push(el.id);
return true;
} else {
// Already present in array, don't add it
return false;
}
});
return uniqueTopics;
};
最佳答案
这可能会有所帮助。
var data = [
{
"id": 1,
"number": 2,
"section": "xx",
"importance": "high",
"applicability": "General",
"text": "some text here",
"topic":
{
"id": 30,
"title": "Gender and Diversity"
}
},
{
"id": 2,
"number": 2.1,
"section": "xx",
"importance": "high",
"applicability": "General",
"text": "some text here",
"topic":
{
"id": 31,
"title": "Health and Safety"
}
}
];
console.log(
data.map(d => { return { "topic": d.topic }; })
);
var data = [
{
"id": 1,
"number": 2,
"section": "xx",
"importance": "high",
"applicability": "General",
"text": "some text here",
"topic":
{
"id": 30,
"title": "Gender and Diversity"
}
},
{
"id": 2,
"number": 2.1,
"section": "xx",
"importance": "high",
"applicability": "General",
"text": "some text here",
"topic":
{
"id": 31,
"title": "Health and Safety"
}
}
];
console.log(
data.map(d => d.topic)
);
关于javascript - 从 AngularJS 中的对象访问所有嵌套值的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59645836/