gpt4 book ai didi

Javascript - 过滤对象中的数组

转载 作者:行者123 更新时间:2023-11-30 08:23:30 25 4
gpt4 key购买 nike

我正在尝试创建一个具有过滤值的对象数组

// desired output

[
{ "2017-02-01": "09:00" },
{ "2017-02-02": "09:00" },
]

我的Js对象

let res = {
"2018-02-01": [
{
"time": "09:00",
"available": true,
},
{
"time": "10:00",
"available": false,
}
],
"2018-02-02": [
{
"time": "09:00",
"available": true,
"reference": null
},
{
"time": "10:00",
"available": false,
"reference": null
}
]
}

// My attempt
output = _.keys(res).map( i => res[i].filter( t => t.available))

console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>

最佳答案

试试这个:

let res = {
"2018-02-01": [
{
time: "09:00",
available: true
},
{
time: "10:00",
available: false
}
],
"2018-02-02": [
{
time: "09:00",
available: true,
reference: null
},
{
time: "10:00",
available: false,
reference: null
}
]
};
let output = Reflect.ownKeys(res).map(key => ({
[key]: res[key].filter(obj => obj.available)[0].time
}));
console.log(output);

你的逻辑基本上是正确的,有一点错误,因为你没有很好地控制 map 函数中的 return value

这就是我所做的:

[key]: /*basically  your code*/[0].time

关于Javascript - 过滤对象中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49685767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com