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

neekobn8  于 2023-06-05  发布在  Node.js
关注(0)|答案(3)|浏览(267)

循环遍历对象数组,找到一个键,然后在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 , 
  }

亲切指导

vc9ivgsu

vc9ivgsu1#

您可以循环遍历数组,然后为每个对象检查它是否具有createdDateTime属性。如果是,则使用新的Date对象更新$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'
  }
});

这段代码将创建一个名为updatedPayloads的新数组,其中日期字符串被Date对象替换。原始payloads阵列将保持不变。

ars1skjm

ars1skjm2#

有很多方法。一个是:

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;
});
9gm1akwq

9gm1akwq3#

可以使用Array.forEach()

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

相关问题