var authors = [
{authorIndex:1, author:"John Steinbeck"},
{authorIndex:2, author:"Franz Kafka"},
{authorIndex:3, author:"J. R. R. Tolkien"},
{authorIndex:4, author:"Charles Dickens"}];
var books = [
{title:"The Grapes of Wrath",authorIndex:4,pubYear:1936},
{title:"The Hobbit",authorIndex:2,pubYear:1937},
{title:"The Trial",authorIndex:1,pubYear:1937},
{title:"A Tale of Two Cities",authorIndex:3,pubYear:1859}];
我想做的是在书中插入作者并与authorsIndex联系
答案 0 :(得分:1)
考虑到您的authors
数组将具有唯一的authorIndex
值,请首先创建一个以authorIndex
作为键并以相关对象为值的对象。然后遍历您的books
数组并使用Object.assign()
合并对象属性:
var authors = [
{authorIndex:1, author:"John Steinbeck"}, {authorIndex:2, author:"Franz Kafka"},
{authorIndex:3, author:"J. R. R. Tolkien"}, {authorIndex:4, author:"Charles Dickens"}
];
var books = [
{title:"The Grapes of Wrath",authorIndex:4,pubYear:1936},
{title:"The Hobbit",authorIndex:2,pubYear:1937},
{title:"The Trial",authorIndex:1,pubYear:1937},
{title:"A Tale of Two Cities",authorIndex:3,pubYear:1859}
];
var authorsObj = authors.reduce((r, c) => (r[c.authorIndex] = c, r), {});
var result = books.map(o => Object.assign(o, authorsObj[o.authorIndex]));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
const result = authors.map(val => {
return Object.assign({}, val, books.filter(v => v.authorIndex === val.authorIndex)[0]);
console.log(result);
});
console.log(result);
这将结合作者和书籍
答案 2 :(得分:0)
books.forEach(function(value,index){
var ind = value.authorIndex;
var matchAuthor = authors.find(function(element){
return element.authorIndex == ind;
});
value.author = matchAuthor.author;
})
有很多解决方案,其中之一就是这个,请检查link
答案 3 :(得分:0)
这是对感兴趣的人使用lodash的另一个简洁选择:
var authors = [{ authorIndex: 1, author: "John Steinbeck" }, { authorIndex: 2, author: "Franz Kafka" }, { authorIndex: 3, author: "J. R. R. Tolkien" }, { authorIndex: 4, author: "Charles Dickens" } ];
var books = [{ title: "The Grapes of Wrath", authorIndex: 4, pubYear: 1936 }, { title: "The Hobbit", authorIndex: 2, pubYear: 1937 }, { title: "The Trial", authorIndex: 1, pubYear: 1937 }, { title: "A Tale of Two Cities", authorIndex: 3, pubYear: 1859 } ];
const aMap = _.keyBy(authors, 'authorIndex')
const result = _.map(books, x => _.merge(x, aMap[x.authorIndex]))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>