Reputation: 143
With 2 arrays (one of numbers and other of objects),
How can I get a specific object's-(size
) value (in other function) without knowing its index (and it's value) in the array only its key
with the shortest and fastest way so I can use that value number ?
If the array is empty except for this specific object, the size
property value will be - 0;
If my question isn't clear please comment and I'll fix it and make it betters.
let firstArray = [ 1, 2 , 10, 23, {size: 890}];
funcExtract(firstArray);
function funcExtract(arr){
// arr ? How to find the object when knowing only its key
}
And with array of objects
let secondArray = [ {a:2}, {b:4 },{size: 700}, {c:5} ];
funcExtract(secondArray);
function funcExtract(arr){
}
Upvotes: 1
Views: 3064
Reputation: 4954
Here's the thing which you can do it:
let key = "size"
let secondArray = [ {a:2}, {b:4 },{size: 700}, {c:5} ];
let firstArray = [ 1, 2 , 10, 23, {size: 890}];
function funcExtract(arr,key){
let filter = arr.filter((x)=> typeof x === "object" && x.hasOwnProperty(key))
console.log(filter[0].size)
}
funcExtract(firstArray,key);
funcExtract(secondArray,key);
Upvotes: 1
Reputation: 5937
You can use the Array#find function:
const test = [1, 2, 3, 4, {key: 5}]
const findOne = test.find(item => item.hasOwnProperty("key"))
console.log(findOne)
Upvotes: 2
Reputation: 7642
let secondArray = [ {a:2}, {b:4 },{size: 700}, {c:5} ];
secondArray.find(o => o.size) // {size: 700}
a.filter(o => o.size) // good if you need to find more than 1 with same key
Upvotes: 0