I am trying to access an object within an object using the key from another object.
I have two objects:
const OutputReference = {Key1: "Some Random String",Key2: "Some Random String"}
const masterKey = {
...
'Key1':{
Label: "Key 1",
view: [1,2,3],
},
'Key2':{
Label: "Key 2",
view: [4,5,6],
},
...
}
OutputReference contains multiple keys and values, and I want match these keys to the keys in masterKey to grab each corresponding 'view'. So far, I use this function to break out OutputReference into a key (k) and value (v):
Object.keys(OutpufReference).filter(([k,v])=>{
...
//code here
...
});
I then want to grab "view" for the corresponding key and store it in an array. I used:
var tempArr = []
tempArr.push(masterKey.k.view)
Making the entire function:
Object.keys(OutpufReference).filter(([k,v])=>{
...
var tempArr = []
tempArr.push(masterKey.k.view)
...
});
The issue is masterKey.k is coming back undefined. Note console.log(k) in this case outputs exactly this: Key1
What I have tried (just to access k):
tempArr.push(masterKey.k)
tempArr.push(masterKey[k])
var temp = JSON.stringify(k)
tempArr.push(masterKey[temp])
Object.keys(masterKey).forEach((v,i)=>{
if(v === k) //k is the index from mapping OutputReference
tempArr.push(masterKey.v)
})
None of these work; all return an undefined object (masterKey.v, masterKey[temp], etc.). Note, when doing console.log() on each of these keys (temp, v, k), it outputs the string Key1. However, using
tempArr.push(masterKey.Key1)
Places the correct value in tempArr (Being the object Key1). This is not ideal however, as there are many keys and values in masterKey and OutputReference only contains a few of them.
Where I looked
I researched mozilla's guide on objects, which led me to my previous attempts Mozilla. I also researched this thread Deleting a property from a javascript object. However it recommends what I have already tried.
I see from this thread that JavaScript objects can only use strings as keys, so why doesn't stringifying my key in
var temp = JSON.stringify(k)
tempArr.push(masterKey[temp])
work?
The final output desired: The array tempArr containing every view that outputReference matched with masterKey (In this case: tempArr = [[1,2,3],[4,5,6])