-1
arraynav= [{
            name: 'Haily',
            age: 30,
            iaId: "a0F1g000002yxT8",
            completed: true
        },
        {
            name: 'John',
            age: 30,
            iaId: "a0F1g000002yxT7",
            
        },];

I want this array to be converted into Object like :

arrnav={a0F1g000002yxT8 : {name: 'John'  ,age: 30 },
        a0F1g000002yxT7 : {name: 'Hailey',age: 30,}}

After this I would like to get the value based on my Key like , If I give arrnav[a0F1g000002yxT8] then it should return to me name,age... Could you please help me how do I achivee this .

1

1 Answer 1

3

This is a job for Array.reduce:

let result = arrnav.reduce(
  (p,{iaId,name,age}) => (p[iaId] = { name, age }, p), {}
)

There's a lot to unpack here, so let's take a look.

Array.reduce(callback, initialValue)

We start with a function, Array.reduce, that takes two parameters, a "callback" (a method to call for each item) and an initial value.

We set the initial value to an empty object ({}), that we'll pack with the key:value pairs.

Next we have (...) => .... This is an Arrow Function, which is shorthand for function(...) { ... }. You'll see this a lot in JavaScript. One important thing to know is that if you don't use {} in an arrow function, the last evaluated result is expanded into a return value.

The callback function for reduce needs two parameters, called previous and value. The previous value is what has been collected up to this point, and value is the current indexed value in the array.

For those two parameters, we wrote:

(p,{iaId,name,age})

Where p is the previous value, and {iaId,name,age} is the value parameter. We're doing something special here, namely destructuring the value parameter. The values from value.iaId, value.name, and value.age are set to local variables in the function scope, called iaId, name, and age.

For the function body, we combine two statements with ,:

(p[iaId] = { name, age }, p)

The comma operator evaluates the left-hand side, then the right-hand side, and returns the right-hand side as the result for the function.

First, we create a new object with {name, age}, and then we assign that new object to p[iaId]. Next, the value p is evaluated and returned to the Array.reduce loop so the next value can be evaluated.

Once you understand how all the pieces fit together, you'll see how this code plays out. You may want to take some time to study the other Array methods, as they're incredibly useful for writing concise code.

1
  • Wow great detailed explanation. Thanks alot for prompt response. It worked for me.
    – user91530
    Aug 29, 2021 at 13:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .