Javascript将数组与数组对象合并

时间:2018-10-10 07:17:25

标签: javascript arrays

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联系

4 个答案:

答案 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>

我们执行keyBy以确保我们有一个供参考的键映射,并且我们对它们进行映射,并且对于每个项目我们都merge