I have a Javascript project in which I am trying to iterate through an Array that is found as a value inside a property, to get the key and from this key get its values from another object.
Right now I can only get the key of the property that contains only one value, I need to get the key of the properties that have arrays as value.
This is the input value:
let asset = "test";
This is the first object I need to get the key that the above value belongs to:
let testData = {
"data1": ["CAR,PLANE"],
"data2":["COUNTRY,CITY"],
"data3":"TEST"
};
This is the second object, from which I have to get the values depending on the previous key:
let dataObj = {
"data1": [
"t1Data1",
"t2Data1",
"t3Data1"
],
"data2": [
"t1Data2",
"t2Data2",
"t3Data2"
],
"data3": [
"t1Data3",
"t2Data3",
"t3Data3"
]
};
This is what I do to get the key:
let res = Object.keys(testData).find(key => testData[key] === asset.toUpperCase());
This is what it returns when the value is a single String:
data3
This is what it returns when the value is inside an array (let asset = "car";):
undefined
This is what I need:
data1
This is what I do to iterate through the array:
for(let getData of testData.data1) {
console.log(getData)
}
I need to iterate through the array when getting the key, but I don't know how to include this in the res variable.
testDatayou may have either a string such as"TEST"or an array such as["CAR,PLANE"]. The condition for the.findonly checks for string to match; and doesn't check for array.testData[key] === asset.toUpperCase()condition is evaluated as truthy when the left-side of===is a string"TEST"and the right-side is another stringtest(which is stored in variableasset). Now, please think about what happens when right-side is stringcar(from variableasset), but left-side is["CAR,PLANE"].forEachon the left side to match the right side, I'm going to try===for"car"will fail because the string contained in the array is"CAR,PLANE". It is one string. So, comparing it for equality (ie,===) will fail. You may need to split the string"CAR,PLANE"into an array of strings and then use equality on each element. Will try to post an answer.