简体   繁体   English

从 object 属性获取日期值 - javascript

[英]Get Date value from object property - javascript

How can i get only the Date without the string value from below object?我如何才能从 object 下面只获取没有字符串值的日期?

0: {2020-09-02: "string_1", 2020-09-03: "string_2"}
1: {2020-09-01: "string_1", 2020-09-05: "string_2"}

My objective is to get the Date only and group them into one array.我的目标是只获取日期并将它们分组到一个数组中。

Expected result: [2020-09-02, 2020-09-03, 2020-09-01, 2020-09-05]预期结果: [2020-09-02, 2020-09-03, 2020-09-01, 2020-09-05]

What I tried so far is using Object.getOwnPropertyNames :到目前为止我尝试的是使用Object.getOwnPropertyNames

console.log('property name: ', Object.getOwnPropertyNames(getDateProperties)) // return ["0","1"]

Is this something possible to achieve?这有可能实现吗?

Use reduce and Object keys to get the dates from the object使用 reduce 和 Object 键从 object 获取日期

 const list = [{ "2020-09-02": "string_1", "2020-09-03": "string_2" }, { "2020-09-01": "string_1", "2020-09-05": "string_2" } ] const result = list.reduce((acc, x) => { const keys = Object.keys(x) acc = [...acc, ...keys] return acc; }, []) console.log(result)

Try this:尝试这个:

 let obj = { 0: {"2020-09-02": "string_1", "2020-09-03": "string_2"}, 1: {"2020-09-01": "string_1", "2020-09-05": "string_2"} } let arr = []; for(var key in obj){ for(var subkey in obj[key]){ arr.push(subkey); } } console.log('property name: ', arr)

You may try like this:你可以这样尝试:

 let obj = { 0: { "2020-09-02": "string_1", "2020-09-03": "string_2" }, 1: { "2020-09-01": "string_1", "2020-09-05": "string_2" } } const resultArray = []; Object.keys(obj).forEach((k) => Object.keys(obj[k]).forEach((dateArg) => resultArray.push(dateArg))); console.log(resultArray);

Quick one-liner快速单线

let obj = {
    0: {"2020-09-02": "string_1", "2020-09-03": "string_2"},
    1: {"2020-09-01": "string_1", "2020-09-05": "string_2"}
}

let output = Object.keys(obj).reduce((acc, key) => [...acc, ...Object.keys(obj[key])], [])

console.log(output)

Use flatMap and Object.keys should simplify使用flatMapObject.keys应该简化

 const list = [ { "2020-09-02": "string_1", "2020-09-03": "string_2", }, { "2020-09-01": "string_1", "2020-09-05": "string_2", }, ]; const res = list.flatMap(Object.keys); console.log(res);

Alternatively, if the input data is object.或者,如果输入数据是 object。

 let obj = { 0: { "2020-09-02": "string_1", "2020-09-03": "string_2" }, 1: { "2020-09-01": "string_1", "2020-09-05": "string_2" } } const res = Object.values(obj).flatMap(Object.keys); console.log(res)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM