Search code examples
javascriptarraysecmascript-6ecmascript-5ecmascript-2016

Update array of objects based on the object passed


I have an array of objects that has the following format,

const options = [
  { key: 1, text: "Name", value: "name", icon: "sort" },
  { key: 2, text: "Time", value: "time", icon: "sort" },
  { key: 3, text: "Type", value: "type", icon: "sort" }
];

Now based on the input passed which of format {fieldName,order} I have to modify the array. Basically order will take two values "asc" or "desc" and the fieldName will take any of the values in the value property of options array.

For Example : { fieldName: "name", order : "asc"} or { fieldName: "type", order: "desc"}

Now basically based this order , I have modify the icon field of the source array for that field.

If order is asc, then change the icon property for that field to sort up .If its order is desc, then change the icon property for that field to sort down

Example

1) sortBy: { fielName: "name", order:"asc"} 

//Output
[
  { key: 1, text: "Name", value: "name", icon: "sort up" },
  { key: 2, text: "Time", value: "time", icon: "sort" },
  { key: 3, text: "Type", value: "type", icon: "sort" }
];

2) sortBy: { fielName: "type", order:"desc"} 

//Output
[
  { key: 1, text: "Name", value: "name", icon: "sort" },
  { key: 2, text: "Time", value: "time", icon: "sort" },
  { key: 3, text: "Type", value: "type", icon: "sort down"}
];

It should update icon only of the field passed to it, and rest fields icon should be set to "sort"

This is what I tried

const options = [
  { key: 1, text: "Name", value: "name", icon: "sort" },
  { key: 2, text: "Time", value: "time", icon: "sort" },
  { key: 3, text: "Type", value: "type", icon: "sort" }
];

function updateArray(obj)
{
   const newArr = options.map(item => {
     if(item.name === obj.fieldName) {
    return {...item, icon: obj.order === "desc" ? "sort-desc" :"sort-asc" };
    }
    return {...item};
   });
   return newArr;
}

Solution

  • Try this

    const options = [
      { key: 1, text: "Name", value: "name", icon: "sort" },
      { key: 2, text: "Time", value: "time", icon: "sort" },
      { key: 3, text: "Type", value: "type", icon: "sort" }
    ];
    function sorta(op,options){
       field =op.fielName
       newarray=[]
       options.forEach(o=>{
         if(o.value==field){
          op.order=="asc"?f="up":f="down"
          o.icon="sort-"+f
          newarray.push(o)
         }
          else newarray.push(o)
      })
         return newarray
    }
    
    console.log(sorta({ fielName: "name", order:"asc"},options ))