2

I am new to 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.

6 Answers 6

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

Its simple. Why complicating by reduce and etc.,

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/

1 Comment

0

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

Comments

0

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

The other error is that you are simply missing to return from your function, resulting in an undefined result

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.

Comments

0

You can use reduce and spread like this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.