簡體   English   中英

Javascript 將對象列表轉換為具有鍵值的 object

[英]Javascript transform list of objects into object with key value

var mappings = [ { character: '1', symbol: '$' }, { character: 's', symbol: '@' } ]

我想把它變成:

{
  1: "$",
  s: "@"
}

在 JavaScript 中是否有任何簡單的方法可以實現這一點?

Extract the values of each object in the array using Array.prototype.map , then construct an object from those entries using Object.fromEntries .

 var mappings = [ { character: '1', symbol: '$' }, { character: 's', symbol: '@' } ] let result = Object.fromEntries(mappings.map(e => Object.values(e))) console.log(result)

 var mappings = [ { character: '1', symbol: '$' }, { character: 's', symbol: '@' } ] const newMappings = mappings.map(item => ({[item.character]: item.symbol})) const reduceMapping = newMappings.reduce((acc, current) => ({...acc, ...current}),{}) console.log(reduceMapping)

暫無
暫無

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

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