iT邦幫忙

1

如何取出物件中重複/不重複的值

在上一篇中寫了關於陣列的做法
假如今天我們將陣列改成物件,該怎麼去實現它呢?
先給一個全域值:

const person = [
  { name: "John", age: 10 },
  { name: "John", age: 20 },
  { name: "Jay", age: 30 },
  { name: "Jay", age: 40 },
  { name: "Jack", age: 50 },
  { name: "Jack", age: 60 },
];

方法一
使用ES6語法 map + filter + indexOf

let newObject =person.map(item => {
  return item.name;
})
console.log(newObject) // ["John", "John", "Jay", "Jay", "Jack", "Jack"]

let value = newObject.filter((item, index) => {
  return newObject.indexOf(item) === index;
})
console.log(value) //["John", "Jay", "Jack"]

方法二
跑for迴圈,遍歷陣列法

let newValue = []
let result = []

person.forEach((item) => {
  newValue.push(item.name)
})

newValue.forEach((item, key) => {
  if(result.indexOf(newValue[key]) === -1) {
    result.push(newValue[key])
  }
})
console.log(result) //["John", "Jay", "Jack"]

方法三
使用Array from搭配new Set的做法

const value = Array.from(new Set(person.map(item => {
  return item.name
})))
console.log(value) //["John", "Jay", "Jack"]

如果還有簡單又好理解的方式,歡迎提出分享唷 謝謝


1 則留言

2
良葛格
iT邦新手 3 級 ‧ 2021-04-06 20:56:25
const persons = [
  { name: "John", age: 10 },
  { name: "John", age: 20 },
  { name: "Jay", age: 30 },
  { name: "Jay", age: 40 },
  { name: "Jack", age: 50 },
  { name: "Jack", age: 60 },
];

const names = Array.from(new Set(persons.map(item => item.name)));
jim55167 iT邦新手 5 級 ‧ 2021-04-07 00:25:16 檢舉

非常感謝良葛格分享做法

我要留言

立即登入留言