[英]Find key from array of objects the includes a key word - JS
So I have an array of objects that look like this:所以我有一个看起来像这样的对象数组:
[
{
Other: 23,
},
{
Choco: 21,
},
{
Vanila: 10,
},
{
"Other - WA": 2,
},
{
Strawbery: 30,
},
];
What needs to be done is I have to sort this by showing:需要做的是我必须通过显示来对此进行排序:
I figured I could create 2 separate arrays by moving all that have key 'Other' there and the rest in a separate one.我想我可以创建 2 个单独的 arrays,方法是把所有有“其他”键的东西和 rest 移到一个单独的地方。 Then I simply sort by value and then join the 2 arrays using spread operator.
然后我简单地按值排序,然后使用扩展运算符加入 2 arrays。 The problem is I can't get it to detect 'Other' in the key and when it does it does it literally not like how 'LIKE' from SQL would do here's the code for now:
问题是我无法让它检测到密钥中的“其他”,当它检测到它时,它实际上并不像 SQL 中的“LIKE”那样做现在的代码:
let other = pgData.contents[6]?.locCounts?.filter((loc) =>
Object.keys(loc).includes("Other")
);
It only returns key with "Other" not "Other - WA" like I want to get everything that has the word "Other" in it regardless of whats in front of it.它只返回带有“Other”而不是“Other - WA”的键,就像我想获得其中包含“Other”一词的所有内容,而不管它前面是什么。
includes()
on an iterator does an exact match against the elements, not a substring match.迭代器上的
includes()
与元素完全匹配,而不是 substring 匹配。 Use find()
with a callback function that performs a substring match.将
find()
与执行 substring 匹配的回调 function 一起使用。 You can use includes
on the key to check for a substring there.您可以使用密钥上的
includes
来检查 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 那里。
Object.keys(loc).find(key => key.includes("Other"))
If you want to make two arrays, you can do it in a single loop instead of using two calls filter()
:如果你想制作两个 arrays,你可以在一个循环中完成,而不是使用两个调用
filter()
:
let other = [];
let not_other = [];
pgData.contents[6]?.locCounts?.forEach(loc => {
if (Object.keys(loc).find(key => key.includes("Other"))) {
other.push(loc);
} else {
not_other.push(loc);
}
I simply modified your code a bit.我只是稍微修改了您的代码。 Here's a one-liner:
这是一个单行:
var arr = [{ Other: 23, }, { Choco: 21, }, { Vanila: 10, }, { "Other - WA": 2, }, { Strawbery: 30, }, ] var newArr = arr.filter(el => Object.keys(el)[0].includes("Other")) console.log(newArr)
you could iterate the items and use include on the values like this:您可以迭代项目并在值上使用 include ,如下所示:
let arrayOfObj = [ { Other: 23, }, { Choco: 21, }, { Vanila: 10, }, { "Other - WA": 2, }, { Strawbery: 30, }, ]; let results = [] arrayOfObj.forEach( (e)=> { keys = Object.keys(e) others = keys.forEach( (e)=> { if (e.includes('Other')) { results.push(e) } }) }) console.log(results)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.