簡體   English   中英

Javascript將數組與數組對象合並

[英]Javascript merging an array with array objects

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

    const result = authors.map(val => {
        return Object.assign({}, val, books.filter(v => v.authorIndex === val.authorIndex)[0]);
        console.log(result);
    });
    console.log(result);

這將使作者和書籍組合在一起

考慮到您的authors數組將具有唯一的authorIndex值,請首先創建一個以authorIndex為鍵,而相關對象為值的對象。 然后遍歷您的books數組,並使用Object.assign()合並對象屬性:

 var authors = [ {authorIndex:1, author:"John Steinbeck"}, {authorIndex:2, author:"Franz Kafka"}, {authorIndex:3, author:"JRR 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; } 

books.forEach(function(value,index){
  var ind = value.authorIndex;
  var matchAuthor = authors.find(function(element){
    return element.authorIndex == ind;
  });
  value.author = matchAuthor.author;
})

有很多解決方案,其中之一就是這個,請檢查鏈接

這是對感興趣的人使用lodash的另一個簡潔選擇:

 var authors = [{ authorIndex: 1, author: "John Steinbeck" }, { authorIndex: 2, author: "Franz Kafka" }, { authorIndex: 3, author: "JRR 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來確保我們有一個鍵映射供參考,並且我們映射了它們,並且對於我們合並的每個項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM