TypeError : undefined is not a function Array.reduce

Jack

New Member
#1
Below code is converting object into {"a":"1","b":"2","c":"3","d":"4","e":"5"}, in reduce it is looping through the array and generates the desired output. But then reduce throws TypeError : undefined is not a function.

I have gone through many links but those are not the solution for my error.

Any type of help is welcome.

Please check the code snippet below
Mã:
let a= {
    "a": ["1", "2"],
    "b": ["2", "2"],
    "c": ["3", "2"],
    "d": ["4", "2"],
    "e": ["5", "2"]
}

const b= Object.assign(...Object.entries(a).map(value => value.map((value1, index) => index == 0 ? value1 : value1[0])).reduce((a, c) => {
    //console.log('c', c);
    a[c[0]] = c[1];
    console.log(a);
    return a;
}, {}));
 

Admin

Administrator
Thành viên BQT
#2
The problem can be reduced to attempting to spread an object into an argument list:
Mã:
let a = {
  "a": ["1", "2"],
  "b": ["2", "2"],
  "c": ["3", "2"],
  "d": ["4", "2"],
  "e": ["5", "2"]
}

const reduceResult = Object.entries(a)
  .map(value => value
    .map((value1, index) => index == 0 ? value1 : value1[0])
  )
  .reduce((a, c) => {
    a[c[0]] = c[1];
    return a;
  }, {});

console.log('about to Object.assign');
const b = Object.assign(
  ...reduceResult
);
Objects can't be spread into argument lists - objects can be only spread into other objects, eg
Mã:
const b = { ...reduceResult };
But there's no need for spreading - just take the result of reduce by itself, and you have what you need. You can also simplify the code by removing the two .maps, and just using reduce by itself:
Mã:
let a = {
  "a": ["1", "2"],
  "b": ["2", "2"],
  "c": ["3", "2"],
  "d": ["4", "2"],
  "e": ["5", "2"]
}

const b = Object.entries(a)
  .reduce((acc, [key, [firstValue]]) => ({...acc, [key]: firstValue}), {})
 
console.log(b);
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top