Se7enSquared
10/18/2019 - 10:50 PM

Find a value in a list of objects

Given a list of JSON objects, look up objects based on property or name

let myList = [
    {
        name: "Object 1",
        key1: "Value1",
        key2: "Value2"
    },
    {
        name: "Object 2",
        key1: "Obj2 Value1",
        key2: "Obj2 Value2",
        key3: "Obj2 Value3"
    },
    {   
        name: "Object 3",
        key1: "Obj3 Value1",
        key2: "Obj3 Value2",
        key3: "Obj3 Value3",
        key4: ["obj3 value4 list[0]", "obj3 value4 list[1]"]
    }

];

// look up based on given property
function lookupObject(prop)
for (let i = 0; i < myList.length; i++){
    return myList[i][prop] || "No such property";
}

// return value based on another property value
// name & firstName refer to the value you want to lookup and the property
// that goes with that value
// prop is the property you want the value for based on the value of the other property
function returnValueBasedOnNameAndProperty(name, prop) { //modify "name"
    for (let i = 0; i < myList.length; i++) {
        if (myList[firstName] === name) { //modify "firstName"
            return myList[i][prop] || "No such property";
        }
    }
    return "No such name" //modify "name"
}

//tests
lookupObject(key2);
returnValueBasedOnName("Object 2", key3);