Retrieving information from object

Depending on which element a user clicks I want to display a modal containing specific information. I figured out, that I need to put my additional information in an Obejct (and not into HTML).
Like this:

const myObjects = [
  { firstName: "Blauzahn", Lives: "800 - 860" },
  { firstName: "Ragnar Lothbrock", Lives: "780 - 860" }
];

I read, that I need to convert this into an array.
const entries = Object.entries(myObjects);

And than I need to loop through the array. I want to find the specific information stored into the myObjects Object - which should match the clicked element.

(chosenObject is the click target)

for (i = 0; i < entries.length; i++) {
chosenObject === entries[i][1].firstName
? console.log(entries[i][1].Lives)
: false;
}

Why do I need the second index ([1]) after [i]? Without it, the code does not work. Is there a cleaner way to do it?

The next step would be to get the information into my modal. Am I on the right track with template literal strings? Like:
let lifetime = entries[i][1].Lives;

Do sth. with${lifetime}like appending it into an DOM element.

Cheers, S

The above is already an array, am I missing something?

No need for Object.entries in this instance.

You could use array’s find method to look for a match. Like this.

// Already an array. No need for object entries
const danishKings = [
  { name: "Blauzahn", lived: "800 - 860" },
  { name: "Ragnar Lothbrock", lived: "780 - 860" }
]

danishKings.find( function (king) {
    return king.name === 'Ragnar Lothbrock'
})

//output : {name: "Ragnar Lothbrock", lived: "780 - 860"}

You would more than likely want to wrap this in a function e.g. findByName(name, kings){…}

A couple of examples.

One using a regex and find

function findKing (name, kings) {
    return kings.find( function (king) {
        return new RegExp(name.trim(), 'i').test(king.name)
    })
}

or a for of loop

// Small utility function to trim and convert names to lowercase
// e.g. '  Ragnar lothbrock ' => 'ragnar lothbrock'
function lowCaseTrim(text) {
  return text.trim().toLowerCase()
}

function findKing (name, kings) {

    for (king of kings) {
      if (lowCaseTrim(king.name) === lowCaseTrim(name)) return king
    }
}

Test:

// test with accidental spacing and a lowercase 'L'
console.log(findKing(' Ragnar lothbrock', danishKings))

// Output: {name: "Ragnar Lothbrock", lived: "780 - 860"}
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.