Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reduce function giving "Uncaught TypeError: Cannot set property 'title' of undefined"

Tags:

javascript

I'm trying to reshape a JSON object in javascript using the reduce function.

As i understand, each time a new property is added to an object in javascript, it must be declared like ac['new_object'] = {};. I'm doing this, so i don't understand why I'm seeing the error: Uncaught TypeError: Cannot set property 'title' of undefined

Reproducible example:

let field_list = [
    {
        "key": "id",
        "val": {
            "boost": 4
        }
    },
    {
        "key": "title",
        "val": {
            "boost": 4
        }
    }
]

field_list.reduce(function(ac, cu){
    ac[cu.key] = {}
    ac[cu.key] = cu.val
}, {})

How can i correctly reduce this JSON object? What was my error here?

Target format:

{
    tales: {
        foo: {"id": 2},
        bar: {"title": 1},
        ...
    }
}
like image 552
Preston Avatar asked Sep 13 '25 18:09

Preston


1 Answers

Don't forget to return the accumulator object at the end of the function:

field_list.reduce(function(ac, cu){
  ac[cu.key] = {}
  ac[cu.key] = cu.val
  return ac; // <---- added return statement
}, {})

Without that, undefined will be implicitly returned, and so the next iteration of the loop will have ac equal to undefined

like image 187
Nicholas Tower Avatar answered Sep 15 '25 08:09

Nicholas Tower