基于JavaScript中的部分字符串匹配过滤对象

时间:2019-04-30 22:45:44

标签: javascript arrays object filter

我正在尝试对此JavaScript对象进行排序,以便仅返回某些行,该对象:

import subprocess
import os

for singleCloneUrl in urlsList:
    os.chdir('your full path here') 
    subprocess.run(['git', 'clone', singleCloneUrl], shell=True)

我只想返回powers部分中具有力量“ Strength”的行,但要返回包含所有数据的完整行,所以我想在完成时使用它:

const baseHeroes = [
  { name: "Batman", powers: ["Strength", "Intelligence"] },
  { name: "Superman", powers: ["Strength", "Flying"] },
  { name: "Spiderman", powers: ["Spider Sense", "Webs"] },
  { name: "The Flash", powers: ["Speed"] },
  { name: "Captain America", powers: ["Strength", "Shield"] },
];

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

Array.filter是您的朋友在这里。除此之外,.includes也是您的朋友:

const baseHeroes = [
  { name: "Batman", powers: ["Strength", "Intelligence"] },
  { name: "Superman", powers: ["Strength", "Flying"] },
  { name: "Spiderman", powers: ["Spider Sense", "Webs"] },
  { name: "The Flash", powers: ["Speed"] },
  { name: "Captain America", powers: ["Strength", "Shield"] },
];

const results = baseHeroes.filter( h => h.powers.includes('Strength') );

console.log(results);

您可能还需要考虑其他事项,例如区分大小写以及.powers为null或数组以外的内容的可能性,但这应该使您大致了解如何进行处理。

答案 1 :(得分:1)

我是JavaScript的新手,但以下方法似乎可行。

const strongHeroes = [];

const baseHeroes = [
  { name: "Batman", powers: ["Strength", "Intelligence"] },
  { name: "Superman", powers: ["Strength", "Flying"] },
  { name: "Spiderman", powers: ["Spider Sense", "Webs"] },
  { name: "The Flash", powers: ["Speed"] },
  { name: "Captain America", powers: ["Strength", "Shield"] },
];

for (var i = 0; i < baseHeroes.length; i++) {
    if (baseHeroes[i].powers.indexOf("Strength") != -1) {
        strongHeroes.push(baseHeroes[i]);
    }
}

基本上,它搜索原始数组,并且如果幂包含字符串“ Strength”,它将返回强度的起始位置,如果找不到,则返回-1。因此,如果我们在力量中找到力量,则将该阵列推入新阵列。

答案 2 :(得分:-1)

您可以执行以下操作:

Array.prototype.containsPattern = function(elem)
{
var results = [];
for (var i in this)
{
    if (this[i].toString().includes(elem))
    {
            results.push(this[i]);
    }
}

return results;
}
var fruits = ["Banana", "Orange", "Apple", "1,Mango", "2,Mango"];

var n = fruits.containsPattern("Mango");

在这种情况下,此函数将返回以下内容:1,Mango,2,Mango。最好的是,您可以自定义函数以执行所需的任何操作。

希望会有所帮助,加油。