根据给定的键将对象数组转换为对象

时间:2019-03-30 08:45:38

标签: javascript arrays object

我是Java语言的新手。

我需要编写一个函数,以使用给定的键将对象的数组转换为对象。

输入是这样的

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');

我们将不胜感激任何帮助。

6 个答案:

答案 0 :(得分:2)

您可以通过映射分配新对象的方式来实现目标。

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'))

答案 1 :(得分:1)

此解决方案对我有用:

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);

答案 2 :(得分:0)

您已经接近了,但是您需要使用嵌套的括号表示法来获取正确的键名,例如

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')
);

答案 3 :(得分:0)

很简单。为什么通过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/

答案 4 :(得分:0)

您的代码几乎可以正常工作,唯一的错误是使用括号表示法访问变量键。例如:

obj[v]将得出obj.idv的值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之后什么也不会发生,因此减速器中的console.log行应在此之前,否则将被忽略。

答案 5 :(得分:0)

您可以像这样使用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);

参考: reduce Spread syntax