如何循环遍历对象数组并根据 JavaScript 中的条件添加新的对象键?

How to loop through array of objects and add new object key based on condition in JavaScript?

我有以下对象数组:

[{"id":0,"name":"Katy","age":22},
{"id":2,"name":"Lucy","age":12},
{"id":1,"name":"Jenna","age":45},
{"id":3,"name":"Ellie","age":34}]

我需要在对象 (PaymentCategory) 中添加另一个键,其中 ID 最低的对象被添加值为“Cash”的键,ID 最高的键“Card”,以及在“支票”之间;然后还必须按 ID 对数组进行排序。

因此所需的输出为:

[{"PaymentCategory":"Cash","id":0,"name":"Katy","age":22},
{"Payment Category":"Cheque","id":1,"name":"Jenna","age":45},
{"Payment Category":"Cheque","id":2,"name":"Lucy","age":12},
{"Payment Category":"Card","id":3,"name":"Ellie","age":34}]

我们如何才能以最有效的方式实现这个结果,即最少的迭代次数,最高的性能?

这是我尝试过的:

const min = array.reduce((prev,curr)=> prev.id<curr.id?prev:curr)
  const max = array.reduce((prev,curr)=> prev.id>curr.id?prev:curr)
  min.PaymentCategory = "Cash"
  max.PaymentCategory = "Credit"
  const result =[min, max]

问题是:

  1. 我循环了两次,一次是 max,一次是 min
  2. 如何获得“中间”值?

你可以这样做

const array =[{"id":0,"name":"Katy","age":22},
{"id":2,"name":"Lucy","age":12},
{"id":1,"name":"Jenna","age":45},
{"id":3,"name":"Ellie","age":34}]

const arrayLength= array.length
  
const newA=array.map( (element,index) =>  { if (index===0) return {"PaymentCategory":"Cash", ...element}
else if ( index===arrayLength-1 )return {"PaymentCategory":"Card", ...element}
else return {"PaymentCategory":"Cheque", ...element}})

查看数组中的映射方法以了解更多信息:https://learnjsx.com/category/2/posts/es6-mapFunction

下面提供的方法很简单,首先 sort the items of a shallow array copy ([...sampleData]) 按 id 值的升序 ( .sort((a, b) => a.id - b.id) )。

最终任务执行 map each (sorted) item in a way which creates a shallow copy ({ ...item }) 并且另外创建一个 'Payment Category' 条目,其中第一项 ( idx === 0 ) 被分配 'Cash' 值,最后一项( (idx === arr.length - 1) ) 被赋予 'Card' 值,所有其他被赋予 'Cheque' 值。

整个方法不会改变最初提供的数据...

const sampleData = [
  { id: 0, name: "Katy", age: 22 },
  { id: 2, name: "Lucy", age: 12 },
  { id: 1, name: "Jenna", age: 45 },
  { id: 3, name: "Ellie", age: 34 },
];

console.log(
  'mapped `sampleData` items ...',

  [...sampleData]
    .sort((a, b) => a.id - b.id)
    .map((item, idx, arr) => ({
      ...item,
      'Payment Category': ((idx === 0)
        && 'Cash') || ((idx === arr.length - 1)
        && 'Card') || 'Cheque',
    }))
);
console.log('unmutated `sampleData` ...', sampleData);
.as-console-wrapper { min-height: 100%!important; top: 0; }

以上方法更易读...

const copyItemAndAugmentPaymentCategory = (item, idx, arr) => ({
  ...item,
  'Payment Category': ((idx === 0)
    && 'Cash') || ((idx === arr.length - 1)
    && 'Card') || 'Cheque',
});
const compareItemIdPrecedenceAscending = (a, b) => a.id - b.id;

console.log(
  [
    { id: 0, name: "Katy", age: 22 },
    { id: 2, name: "Lucy", age: 12 },
    { id: 1, name: "Jenna", age: 45 },
    { id: 3, name: "Ellie", age: 34 },
  ]
  .sort(compareItemIdPrecedenceAscending)
  .map(copyItemAndAugmentPaymentCategory)
);
.as-console-wrapper { min-height: 100%!important; top: 0; }