简体   繁体   English

基于给定键将对象数组转换为对象

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

I am new to Javascript. 我是Javascript的新手。

I need to write a function to covert an array of objects to an object with a given key. 我需要编写一个函数来将一个对象数组转换为一个具有给定键的对象。

The input is like this 输入是这样的

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

and output needs to be like this 和输出需要像这样

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

I have tried the below code. 我试过下面的代码。

When I am trying this directly in console it seems it is working. 当我在控制台中直接尝试这个时,它似乎正在工作。

 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) 

But, when I am trying do it from the function it is not working. 但是,当我尝试从功能中执行它时它不起作用。

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

f(arr, 'role');

Any help will be highly appreciated. 任何帮助将受到高度赞赏。

You could take a dunctional approach by mapping an assigning new object. 您可以通过映射分配新对象来采取功能方法。

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

This solution works for me: 这个解决方案对我有用:

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

You're close, but you need nested bracket notation to get to the proper key name, eg 你很接近,但你需要嵌套的括号表示法来获得正确的密钥名称,例如

prev[current[v]]

or 要么

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

Its simple. 这很简单。 Why complicating by reduce and etc., 为什么通过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/ https://jsfiddle.net/cvydtL7p/

Your code is pretty much working, the only errors are to use bracket notation to access a variable key; 您的代码非常有用,唯一的错误是使用括号表示法访问变量键; for example: 例如:

obj[v] will evaluate to obj.id if v was id 如果vidobj[v]将评估为obj.id

The other error is that you are simply missing to return from your function, resulting in an undefined result 另一个错误是您只是缺少从函数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')); 

Also note that nothing after return will happen, so the console.log line in your reducer should be before that, otherwise it's ignored. 另请注意, return后不会发生任何事情,因此reducer中的console.log行应该在此之前,否则会被忽略。

You can use reduce and spread like this: 您可以像这样使用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 syntax refs: reduce Spread语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM