I have an object called Suppliers where the id is always unique as follows:
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'
}
}
How can I return the sub-object (eg return suppliers.Supplier1) when all I know is the id of the sub object? I tried to use .filter, but that only seems to work on arrays:
function findById(source, id) {
return source.filter(function (obj) {
return +obj.id === +id;
})[0];
}
var supplierarray = findById(suppliers, myKnownID);
return supplierarray;
You need to loop over the object
using for-in
loop, you tried to use .filter
which is for array.
So you can change findById
definition to below
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"}
Object.keys(suppliers).map(key => suppliers[key]).find(({id}) => id === someId);
You can search for any key in its child objects.
Object.prototype.findBy = function(propName, propVal){
for( var i in this ){
if( this[i][ propName ] == propVal ){
return this[i];
}
}
return undefined;
};
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'
}
}
console.log(suppliers.findBy("id",1));
Here i've added function inside prototype of root Object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.