![](/img/trans.png)
[英]convert javascript object into array of objects based on key value array
[英]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')
您的代碼非常有用,唯一的錯誤是使用括號表示法訪問變量鍵; 例如:
如果v
是id
則obj[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
行應該在此之前,否則會被忽略。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.