如何在嵌套对象中找到属性

时间:2018-07-26 11:23:21

标签: javascript lodash

我试图弄清楚如何根据另一个对象内部的对象属性值提取结果

{
   title: 'The Book',
   author: {
      name: 'Merlin Bridge',
      category: 'Fiction'
   }
}  

这是我的测试:

  // this works
  const test1 = _.find(existingBooks, {
    title: uploadedBooks[i].title,
  });

  // this doesn't work and returns nothing
  const test2 = _.find(existingBooks, {
    'author.name': uploadedBooks[i].author.name,
  });

我想得到其中author.name是标识符的结果。非常感谢。

5 个答案:

答案 0 :(得分:3)

您可以使用下面的代码来迭代json对象。

var myObj = {
   title: 'The Book',
   author: {
      name: 'Merlin Bridge',
      category: 'Fiction'
   }
} 
Object.keys(myObj).forEach(key => {
    console.log(JSON.stringify(myObj[key]));
  });

答案 1 :(得分:2)

可以将动态命名的属性添加到JavaScript对象。

假设您要循环数组而不是对象:

var a = _.map(existingBooksArray, function(existingBook) {
    return {[existingBook.author.name]: existingBook.title}
});

a的结果

[
    {
        Merlin Bridge: "The Book"
    }
]

答案 2 :(得分:2)

当您使用Lodash / Underscore find时,我也自由使用了get帮助器。请在下面找到一个对您有帮助的答案。

const books = [{
    title: 'The Book',
    author: {
      name: 'Merlin Bridge',
      category: 'Fiction'
    }
  },
  {
    title: 'Another Book',
    author: {
      name: 'Merlin Window',
      category: 'Science'
    }
  }
];
const uploadedBooks = [{
    title: 'Another Book',
    author: {
      name: 'Merlin Window',
      category: 'Science'
    }
  }];
const i = 0;
const foundBook = _.find(books, (book, index) => {
  return _.get(book, 'author.name') === _.get(uploadedBooks, [i, 'author', 'name'])
});
console.log(foundBook);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

答案 3 :(得分:1)

使用.key方法

Object.keys(myObj).forEach(key => {
console.log(myObj[key]);});

var myObj = {
   title: 'The Book',
   author: {
      name: 'Merlin Bridge',
      category: 'Fiction'
   }
} 

Object.keys(myObj).forEach(key => {
    console.log(JSON.stringify(myObj[key]));
  });

答案 4 :(得分:0)

var myObj = {
   title: 'The Book',
   author: {
      name: 'Merlin Bridge',
      category: 'Fiction'
   }
} 
Object.keys(myObj).forEach(key => {
    console.log(JSON.stringify(myObj[key]));
  });