簡體   English   中英

如何在Lodash中將對象數組轉換為對象?

[英]How to convert an array of objects to an object in Lodash?

我有這個:

    [ { list: 
             [ [Object],
               [Object] ] },
      { head:
             [ [Object],
               [Object] ] }
    ]

並希望將其變成這樣:

    { list: 
                 [ [Object],
                   [Object] ],
      head:      [ [Object],
                   [Object] ]
    }

所以一個對象數組到一個對象中。 用lodash實現這一目標會很棒。

_.reduce(array, function(memo, current) { return _.assign(memo, current) },  {})

我認為更簡短的解決方案是:

Object.assign({}, ...array)

我知道你要求lodash,但看起來你甚至不需要這樣。 除非你想使用_.extend

這是一個較短的版本:

_.transform(array, _.ary(_.extend, 2),  {});

transform()函數就像reduce() ,除了它不期望你返回任何東西。 由於extend()正在改變它的第一個參數,我們可以直接將它傳遞給transform() 它包含在ary()中以確保它只傳遞2個參數。

要建立@ rcsole的好答案,這很有效:

states = [{
  state: "NY",
  name: "New York",
}, {
  state: "AZ",
  name: "Arizona",
}]

statesObj = Object.assign({}, ...states.map(state => { 
  return { [state.state]: state.name } 
}))

結果:

{
  AZ: "Arizona",
  NY: "New York",
}

這里發生了什么?

讓我們分解成多個部分:

// Step 1: Transform from [{state: "Foo", name: "Bar"}, ...] to [{Foo: "Bar"}, ...]
mappedStates = states.map(state => { return { [state.state]: state.name } })

// Step 2: Merge all the objects in that array into a single new object
statesObj = Object.assign({}, ...mappedStates)

步驟1使用map迭代數組中的每個項目(每個狀態對象)。 map為每個state對象執行一個函數,並返回一個新對象,其狀態為鍵,名稱為值。 我們需要在括號中state.state ,因為它是對象文字中的動態值。

步驟2使用Object.assignmappedStates數組中的所有新狀態對象合並為一個新對象(第一個參數{} )。 什么是三個點...呢? 那是傳播運營商。 它接受mappedStates數組中的每個元素,並將它們轉換為Object.assign方法的直接參數。

這個例子清楚地說明了:

Object.assign({}, ...mappedStates)

是相同的

Object.assign({}, {AZ: "Arizona"}, {NY: "New York"})

而已!

在lodash上使用fromPairs 4. https://lodash.com/docs#fromPairs

_.fromPairs([['fred', 30], ['barney', 40]]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM