1

I'm trying to findIndex of an object in an array containing multiple objects. I've been struggling with this for a while and have simplified it to what you see and still cannot get it. Please let me know what will work so that I can get the "input" object's string from matchBetween("string1");

matchBetween("string1");
matchBetween = function (result) {
        let params = [
            { param: "string1", input: "inputstring1"},
            { param: "string2", input: "inputstring2"}
            ];
        console.log(result, params, params.param ); //Output: "string1", (2)[{...}, {...
        let location = params.findIndex (x => Object.is(result, x));
        console.log(location); //outputs -1
        return params[location].input // 'Cannot read property 'input' of undefined'
    }; 

I've attempted multiple things, but I feel like it's an easy fix and I'm just missing it. THank you in advance!

2
  • 1
    you're Object.is is comparing each {param, input} object with a string ... so, clearly there's no match ... x=>x.param == result instead Commented Sep 14, 2017 at 3:45
  • 1
    note: params.param will always be undefined as that's not how arrays of objects works Commented Sep 14, 2017 at 3:46

2 Answers 2

2

Object.is(result, x) is wrong.

Run params.findIndex (x => {console.log(x); return false;}); to see what each x looks like

{param: "string1", input: "inputstring1"}
{param: "string2", input: "inputstring2"}

So you can use Object.is(result, x.param) as Jean mentioned, or result === x.param, or simply

params.find(x => x.param === result).input

Note, you need to handle when result is not found.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this sample:

matchBetween = function (result) {
    let params = [
        { param: "string1", input: "inputstring1"},
        { param: "string2", input: "inputstring2"}
        ];
    console.log(result, params, params[0].param ); //Output: "string1", (2)[{...}, {...x=>x.param == result
    let location = params.findIndex (function(x) { return Object.is(result, x.param); });
    console.log(location); //outputs -1
    return params[location].input // 'Cannot read property 'input' of undefined'
}; 
console.log(matchBetween("string2"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.