Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

javascript - How to print prop name of object filtered by prop value

I have an object

var arr = {
  alfa: {
    name: "a",
    id: "1"
  },
  beta: {
    name: "b",
    id: "2"
  }}

I want to log title of second prop 'beta'

I cant to find prop values with 'find'

Object.values(arr).find(obj => {
  return obj.id === '2'
})

but how I can to extract prop name

in log I want to print like this:

console.log('second prop name is ', extractPropNameById(2))

and result must to be like:

"second prop name is beta"

Object.keys(arr) return only array of props ["alfa", "beta"] and find by id returns undefinded


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As by @GuyIncognito in the comments mentioned you can get the keys and then filter by the id property of the key which you would like to have.

var arr = {
  alfa: {
    name: "a",
    id: "1"
  },
  beta: {
    name: "b",
    id: "2"
  }
}



console.log("second prop name is " + extractPropNameById("2", arr));

function extractPropNameById(searchID, arra) {
  let keys = Object.keys(arra);
  let result = keys.find(key => arra[key].id === searchID);

  return result;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...