gpt4 book ai didi

javascript - 如何从已知子对象 ID 的对象中检索子对象

转载 作者:行者123 更新时间:2023-11-30 15:56:50 25 4
gpt4 key购买 nike

我有一个名为 Suppliers 的对象,其中的 id 始终是唯一的,如下所示:

var suppliers = {
Supplier1: {
id: 1,
name: 'Supplier1',
SVGTemplate: 'svg-supplier1'
},
Supplier2: {
id: 2,
name: 'Supplier2',
SVGTemplate: 'svg-supplier2'
},
Supplier3: {
id: 3,
name: 'Supplier3',
SVGTemplate: 'svg-supplier3'
}
}

当我只知道子对象的 ID 时,如何返回子对象(例如返回 suppliers.Supplier1)?我尝试使用 .filter,但这似乎只适用于数组:

function findById(source, id) {
return source.filter(function (obj) {
return +obj.id === +id;
})[0];
}

var supplierarray = findById(suppliers, myKnownID);
return supplierarray;

最佳答案

您需要使用 for-in 循环遍历 object,您尝试使用用于数组的 .filter

因此您可以将 findById 定义更改为以下

var suppliers = {
Supplier1: {
id: 1,
name: 'Supplier1',
SVGTemplate: 'svg-supplier1'
},
Supplier2: {
id: 2,
name: 'Supplier2',
SVGTemplate: 'svg-supplier2'
},
Supplier3: {
id: 3,
name: 'Supplier3',
SVGTemplate: 'svg-supplier3'
}
}
// Should return single object not array, as id is unique as OP said
function findById(source, id) {
for(var key in source){
if(source[key].id === id){
return source[key];
}
}
return null;
}

findById(suppliers,3);// {id: 3, name: "Supplier3", SVGTemplate: "svg-supplier3"}

关于javascript - 如何从已知子对象 ID 的对象中检索子对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38394369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com