1

I have this code in my function

let packName: string = respPack.find(a => {a.id == 'name_input'}).answer.replace(/ /,'_');

What I'm trying to do is find the object by matching the id and extract the value of it's answer property. As of right now I'm getting an error telling me

cannot read property answer of undefined.

Am I trying to do this the right way? Here's the rest of my function so you can see what's going on.

saveResponses(){
    const respPack = this.ResponseList;
    const sendTarget: FirebaseObjectObservable<any> = this.afdb.object('/submissions');

    let dataLoad:{ [prop : string]: Array<any> } = {};
    let packName: string = respPack.find(a => {a.id == 'name_input'}).answer.replace(/ /,'_');

    respPack.forEach( a => {
        if(a.answer){
            let data = { question: a.question, answer: a.answer, id: a.id };
            dataLoad[packName].push(data);
        }
        else if(a.responses){
            let dataChunk = { question: a.question, id: a.id, responses: Array<any> }; 

            a.responses.forEach(resp => {
                let respChunk = { response: resp.response, value: resp.value, id: resp.id };
                dataChunk.responses.push(respChunk);
            });
            dataLoad[packName].push(dataChunk);
        }
    });

    sendTarget.set(dataLoad);
}
Optiq
  • 2,835
  • 4
  • 33
  • 68

2 Answers2

2

If you're using an arrow function with {} you have to include return.

Eg:

a => {return a.id == 'name_input'} 

Also, find will return undefined if no items are found, you'll have to deal with those cases.

Here is a complete example:

let packName: string = "";
let foundElement = respPack.find(a => {
                              return a.id == 'name_input';
                            });
if(foundElement){
    packName = foundElement.answer.replace(/ /,'_');
}

Or if you want to keep it one line.

let packName: string = ((respPack.find(a => a.id == 'name_input') || {}).answer || "").replace(/ /,'_');
Titus
  • 22,031
  • 1
  • 23
  • 33
1

yourArray.find(element) will retrun the element following is an example

find more about find()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

var inventory = [
    {name: 'apples', quantity: 2},
    {name: 'bananas', quantity: 0},
    {name: 'cherries', quantity: 5}
];

function findCherries(fruit) { 
    return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); 
// { name: 'cherries', quantity: 5 }

You have the issue in your find method calling

a => {return a.id == 'name_input'} 

find more about arrow function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Nisal Edu
  • 7,237
  • 4
  • 28
  • 34