在 javascript 中循环遍历基于键的对象数组并更改其值

Looping through array of object based on a key and change its value in javascript

提问人:Sindhu1990 提问时间:5/31/2023 更新时间:5/31/2023 访问量:54

问:

遍历对象数组,找到一个键,然后在 javascript 中更改其值

嗨,我有一个下面的对象数组

[
  {
    createdDateTime: {
      '$gte': '2023-02-08T00:00:00.000Z',
      '$lte': '2023-05-09T23:59:59.000Z'
    }
  },
  { user: 'customer' }
]

我想把它改成下面

[
  {
    createdDateTime: {
      '$gte':new Date( '2023-02-08T00:00:00.000Z'),
      '$lte':new Date( '2023-05-09T23:59:59.000Z')
    }
  },
  { user: 'customer' }
]

我试过了什么

var check = filtersFromRequest.some(obj => obj.hasOwnProperty("createdDateTime"));
  if(check){
   // stuck here as what to do , 
  }

温馨导游

JavaScript 节点 .js 对象 聚合

评论


答:

1赞 Cody Chang 5/31/2023 #1

您可以遍历数组,然后对于每个对象,检查它是否具有该属性。如果是这样,请使用新的 Date 对象更新 and 值。createdDateTime$gte$lte

这是你如何做到的:

// Assuming payloads is your initial array
const updatedPayloads = payloads.map(obj => {
  if(obj.hasOwnProperty('createdDateTime')) {
    let newObject = {...obj}; // clone the object to avoid modifying original
    if(newObject.createdDateTime.hasOwnProperty('$gte')) {
      newObject.createdDateTime['$gte'] = new Date(newObject.createdDateTime['$gte']);
    }
    if(newObject.createdDateTime.hasOwnProperty('$lte')) {
      newObject.createdDateTime['$lte'] = new Date(newObject.createdDateTime['$lte']);
    }
    return newObject;
  } else {
    return obj; // return object as it is if it does not contain 'createdDateTime'
  }
});

此代码将创建一个新数组,该数组调用的日期字符串替换为 Date 对象。原始数组将保持不变。updatedPayloadspayloads

0赞 titan2gman 5/31/2023 #2

有很多方法。一是:

const firstObject = [
  {
    createdDateTime: {
      '$gte': '2023-02-08T00:00:00.000Z',
      '$lte': '2023-05-09T23:59:59.000Z'
    }
  },
  { user: 'customer' }
];

const secondObject = firstObject.map(obj => {
  if (obj.createdDateTime) {
    obj.createdDateTime['$gte'] = new Date(obj.createdDateTime['$gte']);
    obj.createdDateTime['$lte'] = new Date(obj.createdDateTime['$lte']);
  }

  return obj;
});
0赞 pjaoko 5/31/2023 #3

你可以使用 Array.forEach()

filtersFromRequest.forEach( item =>{
    const createdDateTime = item.createDateTime;
    if( createdDateTime ){
        createdDateTime.$gte = new Date(createdDateTime.$gte);
        createdDateTime.$lte = new Date(createdDateTime.$lte);
    }
});