【发布时间】:2021-07-15 21:58:38
【问题描述】:
使用以下数组:
arrOfOranges =
[{ "kerp": "thisThing", "time": "@ rocks 3"},
{ "kerp": "otherThing", "green": "blah"},
{ "kerp": "thisThing", "time": "(countriesToTheStart ^"},
{ "kerp": "anotherThing", "yellow": "row row"},
{ "kerp": "anotherThing", "yellow": "rigorous"},
{ "kerp": "thisThing", "time": ",,,,"}]
每个项目都有以下永久结构:
[{kerp: ''}] 可以是 3 个值之一:thisThing、otherThing 和 anotherThing。每个对象的另一个键取决于 'kerp' 的值。
如果 kerp: 'thisThing' 那么另一个键是 'time'。 => { "kerp": "thisThing", "time": ""},
如果 kerp: 'otherThing' 那么另一个键是 'green'。 => { "kerp": "otherThing", "green": ""},
如果 kerp: 'anotherThing' 那么另一个键是 'yellow'。 => { "kerp": "anotherThing", "yellow": ""},
我想用“kerp”获取数组中的最后一项:“thisThing”。但是,“时间”键的关联值必须包含一个字母。
例如在上面的数组中,数组中的最后一项有 'kerp': 'thisThing',但是 'time' 不包含字母。
所以我需要从 arrOfOranges 获取这个项目,它是数组中的最后一个项目,带有 kerp: thisThing 和 time,值中有字母:
{"kerp": "thisThing", "time": "(countriesToTheStart ^"}
这是我目前所拥有的:
if (arrOfOranges.filter(a=>a.kerp === "thisThing")) {
// this is just a eay to check if the array contains letters
if(arrOfOranges.time.match(/[\w]+/g)) {
return arrOfOranges.slice(-1)[0];
}
}
但是它没有按预期工作。我怎么能做到这一点?
【问题讨论】:
-
Object.values(arrOfOranges).reverse().filter(f => f.time && /[a-z]/i.test(f.time)).pop()
标签: javascript arrays json key-value