如何从数组中获取不同的属性值?

时间:2017-12-10 13:56:29

标签: javascript arrays

我有这个阵列吗?

var arr = [{id:"1",Name:"Tom"},
           {id:"2",Name:"Jon"},
           {id:"3",Name:"Tom"},
           {id:"4",Name:"Jack"}]

从上面的数组中,我需要将所有现有名称区别开来。

var result = getNamesDistinct(arr);

result应包含结果:

 ["Tom","Jon","Jack"]; 

我的问题是如何从arr中获取所有现有名称?

3 个答案:

答案 0 :(得分:3)

如果Set可用,您只需执行

即可
new Set(arr.map(obj => obj.Name))

(如果需要数组,请将设置传递给Array.from

答案 1 :(得分:1)

您可以通过 Set 对象

来完成

const arr = [
   { id: "1", Name: "Tom" },
   { id: "2", Name: "Jon" },
   { id: "3", Name: "Tom" },
   { id: "4", Name: "Jack" }
];

const uniqueNames = [...new Set(arr.map(item => item.Name))];

console.log(uniqueNames);

或者您可以迭代数组并添加条件以仅获取唯一名称。

const arr = [
   { id: "1", Name: "Tom" },
   { id: "2", Name: "Jon" },
   { id: "3", Name: "Tom" },
   { id: "4", Name: "Jack" }
];

const uniqueNames = arr.reduce(function(arr, item) {

   if(arr.indexOf(item.Name) === -1) {
      arr.push(item.Name);
   }

   return arr;

}, []);

console.log(uniqueNames);

答案 2 :(得分:1)

你可以试试这个

awk '
/^[0-9]+\./{  ##Checking condition here if any line starts from a digit(all together) and with a dot if yes then do following.
  ORS=" "     ##Setting value of ORS(output record separator) as space here.
}
!NF{          ##Checking if value of awk out of the box variable named NF value is NULL here, if yes then do following.
  ORS="\n"    ##Setting the value of ORS(output record separator) as new line here.
};
1;            ##By mentioning 1 here I am making condition TRUE here and not mentioning any action so by default print of current line will happen.
END{
  ORS="";     ##Setting value of ORS(output field separator) as NULL here.
  print RS    ##Printing value of RS which is new line by default.
}
' Input_file  ##Mentioning Input_file here.
相关问题