我有以下对象
{date_created: 1546293600000, num: 370, num2: NaN, num3: 100, category: "C"}
我的输出应该是
{num: 370, num3: 100}
理想情况下,删除date_created,num2和category也会删除值中为null或未定义的任何内容
答案 0 :(得分:2)
Object.keys(obj).filter(key => !isNaN(obj[key]))
let obj = {
date_created: 1546293600000,
num: 370,
num2: NaN,
num3: 100,
category: "C"
}
let keys = Object.keys(obj).filter(key => !isNaN(obj[key]))
let newObj = {}
keys.forEach(key => newObj[key] = obj[key])
console.log(newObj)
答案 1 :(得分:2)
您可以使用curl 'xy.com' --data-binary "$(jq -cn --arg e "$1" '.email=$e')"
过滤掉所有filter
值(不是数字,也包括字符串,对象等)。然后重新映射键以获取值:
NaN
在您的示例中,您过滤了const obj = {date_created: 1546293600000, num: 370, num2: NaN, num3: 100, category: "C"}
const newObj = Object.keys(obj)
.filter(key => !isNaN(obj[key]))
.reduce((acc, key) => {
acc[key] = obj[key];
return acc;
}, {});
console.log(newObj);
,但是您的依据是什么?
答案 2 :(得分:1)
您可以使用Object.keys
属性和filter
var myObject = {
date_created: 1546293600000,
num: 370,
num2: NaN,
num3: 100,
category: "C"
};
var newObject = Object.keys(myObject)
.filter(key => {
return !isNaN(myObject[key]);
}).reduce((output, key) => {
output[key] = obj[key];
return output;
}, {});
关于“ date_created”属性,您可以添加如下内容:
忽略所有名称中带有“日期”的属性,即使它们的值是数字。
var newObject = Object.keys(myObject)
.filter(key => {
if (key.includes("date")) return false;
return !isNaN(myObject[key]);
}).reduce((output, key) => {
output[key] = obj[key];
return output;
}, {});
答案 3 :(得分:1)
您可以使用reduce函数
function getNumbersObj(obj) {
return Object.keys(obj).reduce((newObj, key) => {
const value = obj[key];
if (typeof value === 'number') {
newObj[key] = value
}
return newObj
}, {})
}
编辑:对于date_created
(这是一个数字),您可以明确过滤出密钥
function getNumbersObj(obj) {
return Object.keys(obj).reduce((newObj, key) => {
const value = obj[key];
if (typeof value === 'number' && key !== 'date_created') {
newObj[key] = value
}
return newObj
}, {})
}
答案 4 :(得分:1)
您可以使用带过滤器的循环,仅返回数字
const objects = {
date_created: 1546293600000,
num: 370,
num2: NaN,
num3: 100,
category: 'C'
}
let newObj = Object.keys(objects).filter( key =>
!isNaN(key))
console.log(newObj)
答案 5 :(得分:1)
从效率的角度来看,这不是最佳的解决方案,但这是一个解决方案:
#include <stdio.h>
#include <allegro5/allegro.h>
int main(int argc, char **argv){
ALLEGRO_DISPLAY *display = NULL;
if(!al_init()) {
fprintf(stderr, "failed to initialize allegro!\n");
return -1;
}
display = al_create_display(640, 480);
if(!display) {
fprintf(stderr, "failed to create display!\n");
return -1;
}
al_clear_to_color(al_map_rgb(0,0,0));
al_flip_display();
al_rest(10.0);
al_destroy_display(display);
return 0;
}