Home > Software design >  Filter and update array of objects on condition
Filter and update array of objects on condition

Time:01-07

I am getting documents from mongodb and storing it in books variable. books is an array of objects on which i am trying to iterate but for this example i have kept only one object in books

const books = [{
        "users": [
            {
                "id": "1",
                "dueDate": "2023-01-06T07:28:42.461Z"
            },
            {
                "id": "2",
                "dueDate": "2023-01-08T07:34:46.095Z"
            }
        ],
}]

Here i want to compare dueDate for each object in users array and keep only that object which has dueDate less than current date along with that add an additional key of fine inside that object.

here is the function i wrote for it

books.forEach(function (arrayItem) {
    arrayItem.users = arrayItem.users.filter(
      (user) => user.dueDate < new Date().toISOString()
    );
  });

by this i am able to filter objects less than cuurent date but i cannot add addition key value pair to the object

My answer look like

books=[{
        "users": [
            {
                "id": "63abd9ed787e941505b3a816",
                "dueDate": "2023-01-06T07:28:42.461Z"
            }
        ],
}]

but i want it like this where one day delay has 100 rupees as fine fine = (dueDate-current date)*100

books=[{
        "users": [
            {
                "id": "63abd9ed787e941505b3a816",
                "dueDate": "2023-01-06T07:28:42.461Z",
                "fine":100
            }
        ],
}]

i tried using few things but did not workout for me. Any help is very much appreciated. Thanks in advance.

CodePudding user response:

You can add a map() after filter()in order to add a new field to each object

const books = [{
  users: [
    {
      id: "1",
      dueDate: "2023-01-06T07:28:42.461Z"
    },
    {
      id: "2",
      dueDate: "2023-01-08T07:34:46.095Z"
    },
  ],
}]

books.forEach((arrayItem) => {
    arrayItem.users = arrayItem.users
    .filter((user) => user.dueDate < new Date().toISOString())
    .map((user) => ({ ...user, fine: (new Date() - new Date(user.dueDate)) * 100 }));
  });
  
console.log(books)

CodePudding user response:

use .map

let books=[{
        "users": [
            {
                "id": "63abd9ed787e941505b3a816",
                "dueDate": "2023-01-06T07:28:42.461Z"
            }
        ],
}]

let currDate = new Date().toISOString();
let res =books.map( b => {
    return b.users = b.users.map( u => {
      return (u.dueDate < currDate) ? {...u, fine: 100} : {...u}
    } 
    );
  });

console.log(res)

  • Related