Javascript 从AngularJS中的对象访问所有嵌套值的最快方法
在AngularJS中,我有一个JSON API调用中数千条记录的对象。我需要从每个记录(“主题”)中创建一个只包含一个特定键的新数组,从而生成一个只包含唯一值的数组。foreach循环是实现这一点的唯一方法吗?例如: 数据阵列(arr): 我想要一个包含数千条记录中的主题的数组,如下所示:Javascript 从AngularJS中的对象访问所有嵌套值的最快方法,javascript,arrays,angularjs,foreach,unique,Javascript,Arrays,Angularjs,Foreach,Unique,在AngularJS中,我有一个JSON API调用中数千条记录的对象。我需要从每个记录(“主题”)中创建一个只包含一个特定键的新数组,从而生成一个只包含唯一值的数组。foreach循环是实现这一点的唯一方法吗?例如: 数据阵列(arr): 我想要一个包含数千条记录中的主题的数组,如下所示: "topic": { "id": 30, "title": "Gender and Diversity" }, "topic": { "id": 31, "title":
"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数据=[
{
“id”:1,
“数字”:2,
“节”:“xx”,
“重要性”:“高”,
“适用性”:“一般性”,
“文本”:“此处有一些文本”,
“主题”:
{
“id”:30,
“标题”:“性别与多样性”
}
},
{
“id”:2,
“数字”:2.1,
“节”:“xx”,
“重要性”:“高”,
“适用性”:“一般性”,
“文本”:“此处有一些文本”,
“主题”:
{
“id”:31,
“标题”:“健康与安全”
}
}
];
console.log(
map(d=>{return{“topic”:d.topic};})
);代码>这可能会有所帮助
var数据=[
{
“id”:1,
“数字”:2,
“节”:“xx”,
“重要性”:“高”,
“适用性”:“一般性”,
“文本”:“此处有一些文本”,
“主题”:
{
“id”:30,
“标题”:“性别与多样性”
}
},
{
“id”:2,
“数字”:2.1,
“节”:“xx”,
“重要性”:“高”,
“适用性”:“一般性”,
“文本”:“此处有一些文本”,
“主题”:
{
“id”:31,
“标题”:“健康与安全”
}
}
];
console.log(
map(d=>{return{“topic”:d.topic};})
);代码>
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;
};