Search code examples
javascriptarraysecmascript-6javascript-objects

javascript filter by object key and return value of nested object key


I want to return the value of a key for one of the elements inside the object using a condition:

const raw = {
  item1: { name: 'sdfd1', otherStuff: { book:'sdfd11' } },
  item2: { name: 'sdfd2', otherStuff: { book:'sdfd22' } },
  item3: { name: 'sdfd3', otherStuff: { book:'sdfd33' } }
};


var anotherOne = {
  country1 : { city: 'one', item: 'item3'},
  country2 : { city: 'two', item: 'item4'}
}

var searchTerm = anotherOne.country1.item; // item3
var secondTerm = someUser.otherInfo // 'otherStuff'
var result = Object.keys(raw)
  .filter(key => { 
  if (key === searchTerm){
   return raw[searchTerm][secondTerm].book
  }})

  console.log('result:' result); // sdfd33

Basically, i want to look for the searchTerm in the keys of the object raw, and return the value for the book key. In this example, it should return sdfd33. My attempt is returning nothing.

updated:

updated the question.


Solution

  • Use square bracket [] while accessing a object key through a variable. Hopefully the filter & Object.keys will not be required in this case

    const raw = {
      item1: {
        name: 'sdfd1',
        book: 'sdfd11'
      },
      item2: {
        name: 'sdfd2',
        book: 'sdfd22'
      },
      item3: {
        name: 'sdfd3',
        book: 'sdfd33'
      }
    };
    
    var searchTerm = 'item3';
    //using square bracket when acceing key using variable
    var result = raw[searchTerm].book
    console.log(result);