var testData = [{'date': '10:45', 'electricity': 0.49, 'temp': 49},
{'date': '11:00', 'electricity': 0.14, 'temp': 50},
{'date': '11:15', 'electricity': 0.87, 'temp': 35}]
function findData(time){
testData.forEach(function(item){
if(item['date'] == time){
console.log('item: ', item);
var result = new Array(item['electricity'], item['temp'])
console.log('result: ', result)
return result;
}
})
}
var a = findData('10:45');
console.log(a)
Any idea why console.log(a) gives undefined? I have done some research but didn't get the answer:(
You can not return from a callback for Array#forEach and you need at least a return statment in the function block to get a different value as undefined.
Instead, you could find the object with Array#find, destructure the wanted properties and return an array of values.
function findData(data, time) {
const result = data.find(({ date }) => date === time);
if (result) {
const { electricity, temp } = result;
return [electricity, temp];
}
}
var testData = [{ date: '10:45', electricity: 0.49, temp: 49 }, { date: '11:00', electricity: 0.14, temp: 50 }, { date: '11:15', electricity: 0.87, temp: 35 }]
var a = findData(testData, '10:45');
console.log(a)
Your function needs to return something. Also, returning something from the forEach() callback won't do it; you have to store that result in a variable that is visible to findData():
function findData(time){
var r;
testData.forEach(function(item){
if(item['date'] == time){
console.log('item: ', item);
var result = new Array(item['electricity'], item['temp'])
console.log('result: ', result)
r = result;
}
})
return r;
}
Because you didn't stop the forEach loop after it found result, so the loop keep going to the next index. There are many ways to achieve the result you need. Array.find is one way.
var testData = [{'date': '10:45', 'electricity': 0.49, 'temp': 49},
{'date': '11:00', 'electricity': 0.14, 'temp': 50},
{'date': '11:15', 'electricity': 0.87, 'temp': 35}]
function findData(time){
const foundItem = testData.find(function(item){
return item['date'] == time;
});
console.log('item: ', foundItem);
const result = new Array(foundItem['electricity'], foundItem['temp'])
console.log('result: ', result)
return result;
}
var a = findData('10:45');
console.log(a)