iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 15
0
自我挑戰組

利用30分鐘~想一個前端問題系列 第 15

利用30分鐘~想一個前端問題 Day15-dig

  • 分享至 

  • twitterImage
  •  

dig

Returns the target value in a nested

Use the in operator to check if target exists in obj.
If found, return the value of obj[target], otherwise use Object.values(obj) and Array.prototype.reduce() to recursively call dig on each nested object until the first matching key/value pair is found.

如何在巢狀的資料下找到目標的值,依照步驟進行,
1.使用 in 運算符 找到 物件裡面指定的屬性
2.沒有的話 就是使用 Object.values(obj) 和 Array.prototype.reduce() 遞迴 到 object 找到相對應的 鍵/值

const dig = (obj, target) =>
  target in obj
    ? obj[target]
    : Object.values(obj).reduce((acc, val) => {
        if (acc !== undefined) return acc;
        if (typeof val === 'object') return dig(val, target);
      }, undefined);
//EXAMPLES
const data = {
  level1: {
    level2: {
      level3: 'some data'
    }
  }
};

dig(data, 'level3'); // 'some data'
dig(data, 'level4'); // undefined

分析點

  1. in 運算符

指定的屬性在指定的對像或其原型鏈中,則in 運算符返回true

const car = { make: 'Honda', model: 'Accord', year: 1998 };

console.log('make' in car);
// expected output: true

delete car.make;
if ('make' in car === false) {
  car.make = 'Suzuki';
}

console.log(car.make);
// expected output: "Suzuki"

in 右操作數必須是一個對象值。例如,你可以指定使用String構造函數創建的字符串,但不能指定字符串文字

  1. Object.values(obj)

在物件下取得 value 的陣列
在這一連串資料下取得 value 之特性屬性的陣列。常常用在物件裡面有物件的狀況。

var obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]
  1. Array.prototype.reduce()

array.reduce(function(accumulator , currentValue, currentIndex, arr),initialValue)

reduce() 是一個比較難以理解的概念,其核心概念就是聚合(一群小分子合併成大分子)有很多種用法,最常看到用在累計總加上。

  • accumulator - 上一輪累計加總
  • currentValue -陣列中正在處理的元素
  • currentIndex - 陣列中正在處理的當前元素的索引(可省略)
  • array - 陣列內容(可省略)
  • initialValue - 累計處理的結果

計算相同元素數量並以物件鍵值顯示,裡面使用條件判斷

var arr =['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var Narr = arr.reduce(function (sum, el) { 
  if (el in sum) {
    sum[el]++;
  }
  else {
    sum[el] = 1;
  }
  return sum;
}, {});

// countedNames is: 出現在陣列就就累加的規則
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

參考資料

MDN in..運算符

MDN Object.value()

MDN Array.prototype.reduce()


上一篇
利用30分鐘~想一個前端問題 Day14--sleep
下一篇
利用30分鐘~想一個前端問題 Day16-similarity
系列文
利用30分鐘~想一個前端問題30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言