我有一个这样的JSON对象:
var x = {
zy5EwY0caL3rPk4PXyX3: { name: 'Bob', completedDate: '2019-03-27T01:56:27.589Z'},
zy4HsKbHYZKtZNBMHdxu: { name: 'Tom', completedDate: '2019-04-10T01:56:27.589Z'},
zy0VPwMY51ksZaTFFIxL: { name: 'Jim', completedDate: '2019-05-01T01:56:27.589Z'},
zw6Xmv5PiNE4dmC19q2p: { name: 'Joe', completedDate: '2019-05-02T01:56:27.589Z'}
}
我想在节点脚本中运行一些JavaScript来过滤并仅返回过去10天内完成数据的对象,然后返回以下内容。
var filteredData = {
zy0VPwMY51ksZaTFFIxL: { name: 'Jim', completedDate: '2019-05-01T01:56:27.589Z'},
zw6Xmv5PiNE4dmC19q2p: { name: 'Joe', completedDate: '2019-05-02T01:56:27.589Z'}
}
我遇到了问题,因为数据是嵌套的。我已经尝试在下划线中使用.where函数,但是我不知道让它检查嵌套元素的语法。
有一种简单的方法来获取我想要的东西吗?
答案 0 :(得分:1)
由于源数据不是数组,因此不能使用Array.filter
。
所以您可以做的是使用Object.entries
进行迭代,然后将其放置到另一个对象中。
下面是一个简单的例子。
const x = {
zy5EwY0caL3rPk4PXyX3: { name: 'Bob', completedDate: '2019-03-27T01:56:27.589Z'},
zy4HsKbHYZKtZNBMHdxu: { name: 'Tom', completedDate: '2019-04-10T01:56:27.589Z'},
zy0VPwMY51ksZaTFFIxL: { name: 'Jim', completedDate: '2019-05-01T01:56:27.589Z'},
zw6Xmv5PiNE4dmC19q2p: { name: 'Joe', completedDate: '2019-05-02T01:56:27.589Z'}
};
const day = 1000 * 60 * 60 * 24;
//const now = Date.now();
//let's set a date time, so snippet will continue to work
//in the future, but Date.now() would be use
//for current time
const now = new Date("2019-05-08T14:29:27.589Z");
const ret = {};
for (const [k, v] of Object.entries(x)) {
const tmc = new Date(v.completedDate);
const diff = Math.abs(tmc.getTime() - now);
if (diff < 10 * day) ret[k] = v;
}
console.log(ret);