我知道以前也有人问过类似的问题,但这个问题有点不同。我有一个未命名对象的数组,其中包含一个命名对象的数组,我需要得到其中“name”为“string 1”的对象。下面是一个示例数组。
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
更新:我应该早点说,但一旦我找到它,我想用一个编辑过的对象替换它。
考虑到您有以下片段:
var array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
您可以使用以下函数来搜索项目
const search = what => array.find(element => element.name === what);
您可以检查是否找到了该项目。
const found = search("string1");
if (found) {
console.log(found.value, found.other);
} else {
console.log('No result found');
}
你可以使用npm中的查询对象。您可以使用筛选器搜索对象数组。
const queryable = require('query-objects');
const users = [
{
firstName: 'George',
lastName: 'Eracleous',
age: 28
},
{
firstName: 'Erica',
lastName: 'Archer',
age: 50
},
{
firstName: 'Leo',
lastName: 'Andrews',
age: 20
}
];
const filters = [
{
field: 'age',
value: 30,
operator: 'lt'
},
{
field: 'firstName',
value: 'Erica',
operator: 'equals'
}
];
// Filter all users that are less than 30 years old AND their first name is Erica
const res = queryable(users).and(filters);
// Filter all users that are less than 30 years old OR their first name is Erica
const res = queryable(users).or(filters);