简体   繁体   English

如何以分配内部对象的方式连接数组?

[英]How to concatenate arrays in the way the objects inside are assigned?

Okay it was a bit hard to explain what I want. 好吧,要我解释一下有点困难。 Let me explain in more detail. 让我更详细地解释。 I have an array of objects. 我有一个对象数组。 Because the "only" identifier of the arrays elements are their indexes, if we want to change an element we need to know which is the target index. 因为数组元素的“唯一”标识符是它们的索引,所以如果要更改元素,我们需要知道哪个是目标索引。 But even if we have the index, I don't want to change the whole object, just assign the new one and "merge" them together. 但是,即使我们有索引,我也不想更改整个对象,只需分配新对象并将其“合并”在一起。

I have a solution, which is ugly, but at least makes more sense what I want: 我有一个丑陋的解决方案,但至少对我想要的东西更有意义:

 const users = [ { id: 0, name: "John", hobby: "soccer" }, { id: 1, name: "Alice", hobby: "squash" }, { id: 2, name: "Greg", hobby: "guitar" } ] const newUsers = [ { id: 0, work: "developer" }, { id: 2, work: "musician" }, { id: 3, name: "Roger", work: "accountant" } ] const concatArray = (newArray, oldArray) => { const objectFromArray = array => array.reduce((object, user) => { object[user.id] = user; return object }, {}); const objectOfOldArray = objectFromArray(oldArray); const objectOfNewArray = objectFromArray(newArray); const allIds = Object.keys({...objectOfOldArray, ...objectOfNewArray}) return allIds.map(id => { const oldProps = objectOfOldArray[id] || {}; const newProps = objectOfNewArray[id] || {}; return {id, ...oldProps, ...newProps} }) } console.log(concatArray(newUsers, users)) 

It works fine, but there should be a more sufficient solution for this. 它工作正常,但是应该有一个更充分的解决方案。 I mean it's a very small operation, adding some properties to the specified objects, but my solution is too over-complicated to earn this. 我的意思是,这是一个非常小的操作,向指定的对象添加了一些属性,但是我的解决方案过于复杂,无法实现这一目标。 There should be an easier way to earn this. 应该有一种更简单的方法来赚钱。

You can try below approach of Array.forEach 您可以尝试以下Array.forEach方法

 const users = [ { id: 0, name: "John", hobby: "soccer" }, { id: 1, name: "Alice", hobby: "squash" }, { id: 2, name: "Greg", hobby: "guitar" } ] const newUsers = [ { id: 0, work: "developer" }, { id: 2, work: "musician" }, { id: 3, name: "Roger", work: "accountant" } ] let updatedUsers = {}; [...users, ...newUsers].forEach(d => updatedUsers[d.id] = { ...(updatedUsers[d.id] || {}), ...d }) console.log(Object.values(updatedUsers)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM