簡體   English   中英

基於給定鍵將對象數組轉換為對象

[英]convert an array of objects to an object based on a given key

我是Javascript的新手。

我需要編寫一個函數來將一個對象數組轉換為一個具有給定鍵的對象。

輸入是這樣的

convert([{id: 1, value: 'abc'}, {id: 2, value: 'xyz'}], 'id')

和輸出需要像這樣

{
    '1': {id: 1, value: 'abc'},
    '2': {id: 2, value: 'xyz'}
}

我試過下面的代碼。

當我在控制台中直接嘗試這個時,它似乎正在工作。

 var arr = [{ id: 1, name: 'John', role: 'Developer'}, { id: 2, name: 'Jane', role: 'Lead'}, { id: 3, name: 'Robbie', role: 'QA'}]; let res = arr.reduce((prev, current) => { prev[current.v] = current; return prev; }, {}) console.log(res) 

但是,當我嘗試從功能中執行它時它不起作用。

function f(k, v) {
  //console.log(k);              
  k.reduce((prev, current) => {
    prev[current.v] = current;
    return prev;
    console.log(prev)
  }, {})
}

f(arr, 'role');

任何幫助將受到高度贊賞。

您可以通過映射分配新對象來采取功能方法。

 function convert(array, key) { return Object.assign(...array.map(o => ({ [o[key]]: o }))); } console.log(convert([{ id: 1, value: 'abc' }, { id: 2, value: 'xyz' }], 'id')) 

這個解決方案對我有用:

function convert(obj, key) {
    var newObj = {};
    obj.forEach(element => {
        newObj[element[key]] = element;
    });
    return newObj;
}

var newObj = convert([{id: 1, value: 'abc'}, {id: 2, value: 'xyz'}], 'id');

console.log(newObj);

你很接近,但你需要嵌套的括號表示法來獲得正確的密鑰名稱,例如

prev[current[v]]

要么

a[item[keyName]] // as in code below

 const convert = (arr, keyName) => arr.reduce((a, item) => { a[item[keyName]] = item; return a; }, {}); console.log( convert([{id: 1, value: 'abc'}, {id: 2, value: 'xyz'}], 'id') ); 

這很簡單。 為什么通過reduce等復雜化,

 function convert(arr, key) { output = {}; arr.forEach(function(item) { output[item[key]] = item; }) console.log(output) return output } convert([{id: 1, value: 'abc'}, {id: 2, value: 'xyz'}], 'id') 

https://jsfiddle.net/cvydtL7p/

您的代碼非常有用,唯一的錯誤是使用括號表示法訪問變量鍵; 例如:

如果vidobj[v]將評估為obj.id

另一個錯誤是您只是缺少從函數return ,導致undefined結果

 var arr = [{ id: 1, name: 'John', role: 'Developer'}, { id: 2, name: 'Jane', role: 'Lead'}, { id: 3, name: 'Robbie', role: 'QA'}]; function f(k, v) { //console.log(k); return k.reduce((prev, current) => { prev[current[v]] = current; return prev; }, {}) } console.log(f(arr, 'role')); 

另請注意, return后不會發生任何事情,因此reducer中的console.log行應該在此之前,否則會被忽略。

您可以像這樣使用reducespread

 var arr = [{id: 1, value: 'abc'}, {id: 2, value: 'xyz'}]; const res = arr.reduce((total, curr) => { return {...total, [curr.id]: curr }; }, {}); console.log(res); 

refs: reduce Spread語法

暫無
暫無

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

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