How to change an object value based on some conditions

Viewed 49

I have the below object and want to change hidden:true based arr values.

obj1 = {
  "items":[
    {name: "Dashboard", url: "/dashboard"},
    {name: "Admin", url: "/admin", attributes: {hidden:false}},
    {name: "User", url: "/user", attributes: {hidden:false}}
  ]
}

arr=["Admin","User"]

I want the result to be like this:

obj1 = {
  "items":[
    {name: "Dashboard", url: "/dashboard"},
    {name: "Admin", url: "/admin", attributes: {hidden:true}},
    {name: "User", url: "/admin", attributes: {hidden:true}}
  ]
}
2 Answers

You can try this,

let obj1 = {
  "items":[
    {name: "Dashboard", url: "/dashboard"},
    {name: "Admin", url: "/admin", attributes: {hidden:false}},
    {name: "User", url: "/user", attributes: {hidden:false}}
  ]
};

let arr=["Admin","User"];

obj1.items.map((item)=>{
    if(arr.includes(item.name)){
      item.attributes.hidden = true;
    }
    return item
});

console.log(obj1)

we first iterate over items and if it has a attribute and the attribute found in arr then we set it to true

obj1 = {
"items":[
{name: "Dashboard", url: "/dashboard"},
{name: "Admin", url: "/admin", attributes: {hidden:false}},
{name: "User", url: "/user", attributes: {hidden:false}}
]
}

arr=["Admin","User"]

let newObject = obj1.items.map( item => {
  if(item.attributes)
    item.attributes.hidden = arr.indexOf(item.name) > -1;
  return item
})

console.log(newObject)

Related