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}];
What I want to do is insert authors in books and to be connected with authorsIndex
-
2please add the result and the code, you tried. --> minimal reproducible exampleNina Scholz– Nina Scholz2018年10月10日 07:18:43 +00:00Commented Oct 10, 2018 at 7:18
4 Answers 4
Considering your authors array will have unique authorIndex values, first create an object having authorIndex as keys and relevant object as its value. Then iterate over your books array and merge object properties using 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; }
Comments
const result = authors.map(val => {
return Object.assign({}, val, books.filter(v => v.authorIndex === val.authorIndex)[0]);
console.log(result);
});
console.log(result);
This is will give the combined array of both authors and books
Comments
books.forEach(function(value,index){
var ind = value.authorIndex;
var matchAuthor = authors.find(function(element){
return element.authorIndex == ind;
});
value.author = matchAuthor.author;
})
There are a lot of solutions one of them is this, Please check the link
Comments
Here is another concise option using lodash for those who are interested:
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>
We do keyBy to make sure we have a key map for reference and them we map and for each item we do merge.