[英]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.