根据传递的对象更新对象数组

Update array of objects based on the object passed

我有一个具有以下格式的对象数组,

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" }
];

现在根据输入的格式{fieldName,order} 我必须修改数组。基本上 order 将采用两个值“asc”或“desc”,fieldName 将采用选项数组 value 属性 中的任何值。

例如:{ fieldName: "name", order : "asc"} 或 { fieldName: "type", order: "desc"}

现在基本上是根据这个顺序,修改源数组的icon字段为那个字段

如果 orderasc,则将该字段的 icon 属性 更改为 sort up。如果它的顺序是 desc,然后将该字段的 icon 属性 更改为 sort down

例子

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"}
];

它应该只更新 icon 传递给它的字段,其余字段 icon 应该设置为“排序”

这是我试过的

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;
}

试试这个

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 ))

您的功能有效,但您正试图访问一个不存在的 属性。

我认为应该是:

if(item.value === obj.fieldName) {
  ...
}

演示:

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.value === obj.fieldName) {
    return {...item, icon: obj.order === "desc" ? "sort-desc" :"sort-asc" };
    }
    return {...item};
   });
   return newArr;
};

console.log(updateArray({fieldName: 'type', order: 'desc'}));
console.log(updateArray({fieldName: 'time', order: 'asc'}));
console.log(updateArray({fieldName: 'name', order: 'desc'}));