簡體   English   中英

如何將 object 推送到同一陣列 javascript 中的另一個 object?

[英]How to push an object to another object in the same array javascript?

我有一個這樣的數組:

[
        {
            "ID": 227886,
            "post_author": "54"
        },
        {
            "ID": 227545,
            "post_author": "18"
        },
        {
            "ID": 229317,
            "post_author": "22"
        },
        {
            "img": "bang.jpg",
            "id": 229317
        },
        {
            "img": "other.png",
            "id": 227886
        },
        {
            "img": "name.jpg",
            "id": 227545
        }
]

我想將所有具有“img”的對象推送到它們的“ID”等於“img”對象的“id”的對象。

預期結果:

[
        {
            "ID": 227886,
            "post_author": "54",
            "img": "other.png",
            "id": 227886
        },
        {
            "ID": 227545,
            "post_author": "18"
            "img": "name.jpg",
            "id": 227545
        },
        {
            "ID": 229317,
            "post_author": "22",
            "img": "bang.jpg",
            "id": 229317
        }  
]

如何將對象推入同一數組中的其他對象中,它們的“id”和“ID”相同?

您可以使用reduceIDid分組,然后將Object.values從Object.values中形成數組。

 const arr = [ { "ID": 227886, "post_author": "54" }, { "ID": 227545, "post_author": "18" }, { "ID": 229317, "post_author": "22" }, { "img": "bang.jpg", "id": 229317 }, { "img": "other.png", "id": 227886 }, { "img": "name.jpg", "id": 227545 }]; const result = Object.values(arr.reduce((a, o)=>{ if(o.ID){ a[o.ID] = {...(a[o.ID] || {}),...o}; } else { a[o.id] = {...(a[o.id] || {}),...o}; }; return a; },{})); console.log(result);

創建一個新數組,其中僅包含帶有帖子作者的對象,而另一個沒有:

const postAuthorList = initialArray.filter(obj => obj.hasOwnProperty('post_author'));
const imgList = initialArray.filter(obj => !obj.hasOwnProperty('post_author'));

然后您可以遍歷postAuthorList ,並從 imgList 中找到匹配的imgList並通過Object.assign()將它們組合起來:

postAuthorList.forEach(postAuthor => Object.assign(postAuthor, imgList.find(img => img.id === postAuthor.ID)))

postAuthorList現在將包含合並列表。 您編寫的確切代碼可能會有所不同,但這些是我將采取的一般步驟。

您可以對b數組使用Object.assigna數組的map()方法來執行此操作。 像那樣:

let c = a.map((row, index) => Object.assign({}, row, b[index]));

完整片段:

 let a = [ { ID: 227886, post_author: "54", }, { ID: 227545, post_author: "18", }, { ID: 229317, post_author: "22", }, { img: "bang.jpg", id: 229317, }, { img: "other.png", id: 227886, }, { img: "name.jpg", id: 227545, }, ]; let b = [ { img: "other.png", id: 227886, }, { img: "name.jpg", id: 227545, }, { img: "bang.jpg", id: 229317, }, ]; let c = a.map((row, index) => Object.assign({}, row, b[index])); console.log(c);

暫無
暫無

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

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