Home > Software design >  How to get values from a object
How to get values from a object

Time:08-24

I am new at Javascript and I'm trying to get values of id key, from array that have multi objects inthere.

dynamicList = [
    { id: 1, gorevAdi: "Görev 1" },
    { id: 2, gorevAdi: "Görev 2" },
    { id: 3, gorevAdi: "Görev 3" },
  ];

Via the for..in loop, I need the id of the objects -like 1,2 or 3- to compare with different values.

I try to do that like that:

function deleteTask(id) {
 
        let deletedId;
        for (let index in dynamicList) {
            if (dynamicList[index].id == id) {
              deletedId = index 
            }
        }
        
        dynamicList.splice(deletedId, 1);
        displayTasks() 
            }

But wehen I did that like this the deleteId value returns undefined.

Icant figur it out why is return undefined and I cant solve that.

I hope I expressed myself well, sorry for my poor english.

CodePudding user response:

You can use filter function.

const dynamicList = [{
    id: 1,
    gorevAdi: "Görev 1"
  },
  {
    id: 2,
    gorevAdi: "Görev 2"
  },
  {
    id: 3,
    gorevAdi: "Görev 3"
  },
];


function deleteTask(id) {
  const newList = dynamicList.filter(e => e.id !== id);
  console.log(newList)
}

deleteTask(1)

CodePudding user response:

Since dynamicList is an array - for in is not recommended ( you can check more here Why is using "for...in" for array iteration a bad idea? )

There are multiple array methods that you can use; in your case filter method is better:

 function deleteTask(id) {
 
        const shallowArray = dynamicList.filter( obj => obj.id !== id);

        displayTasks() 
      }

Also it is usually better not to mutate the data directly, but to create a copy

  • Related