我想创建一个带有嵌套数组的对象,看起来像这样:
[{"name":"Joe","role":["Admin","Developer"]},{"name":"Sherry","role":["Analyst","QA-tester"]}]
我希望能够执行一些操作,例如为 Sherry 查找 Angular 色数组并向该数组添加更多值。我该怎么做?
employees = [];
// [*query database for names and associated roles*]
employees.push({name: exampleVar1,role:exampleVar2});
预期结果:我想存储可用于插入与员工关联的 Angular 色的名称。然后稍后使用此对象作为引用。
最佳答案
您可以使用 Array.find(....)找到你想添加 Angular 色的对象,这里是一个例子:
const arr = [{"name":"Joe","role":["Admin","Developer"]},{"name":"Sherry","role":["Analyst","QA-tester"]}]
const nameToFind = 'Sherry';
const newRole = 'Admin';
const found = arr.find(({ name }) => name === nameToFind);
if (found) {
found.role.push(newRole);
}
console.log(arr);
关于javascript - 如何将数组值插入对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57810359/