用对象转换数组

时间:2015-12-23 10:10:37

标签: javascript arrays

好的,我有2个阵列:

var state = {
  users: [
    {id: 1, name: 'Igor'},
    {id: 2, name: 'Anton'},
    {id: 3, name: 'Vasya'},
    {id: 4, name: 'Pete'},
    {id: 5, name: 'Dan'}
  ],

  chats: [
    {id: 1, users: [1,2], owner: 1},
    {id: 2, users: [1,2,3], owner: 2},
    {id: 3, users: [3,4,5], owner: 5}
  ]
}

我需要一个返回数组的函数,比如'聊天',但实际的名称,而不是ids。 到目前为止我得到了这个:

function loadChats() {
  return state.chats.map(item =>
      ({
        id: item.id,
        users: item.users.map(user => 
          state.users.find(usr => 
            usr.id === user).name),
        owner: item.owner       
      })
    )
}

但我认为解决方案很好,因为我们不需要映射所有数组,只需要'用户'。所以有人建议更好的解决方案吗? 我在想这样做:

...  
state.chats.forEach(item =>
  item.users.map(user => 
    state.users.find(usr => 
      usr.id === user)
  )
)
...

但我不喜欢使用forEach,还有更好的解决方案吗?

2 个答案:

答案 0 :(得分:2)

你可能最好先减少用户数组,然后直接通过id引用人员,这样你只需要遍历用户数组一次。每次聊天都在数组中找到用户是没有用的。

var users = state.users.reduce(function ( map, account ) {
        map[account.id] = account.name;
        return map;
    }, {}),
    conversations = state.chats.map(function ( chat ) {
        return {
            'id' : chat.id,
            'users' : chat.users.map(function ( id ) {
                return users[id];
            }),
            'owner' : users[chat.owner]
        };
    });

答案 1 :(得分:0)

您正在使用箭头功能,因此我猜您可以使用[].find()



var state = {
    users: [
        { id: 1, name: 'Igor' },
        { id: 2, name: 'Anton' },
        { id: 3, name: 'Vasya' },
        { id: 4, name: 'Pete' },
        { id: 5, name: 'Dan' }
    ],

    chats: [
        { id: 1, users: [1, 2], owner: 1 },
        { id: 2, users: [1, 2, 3], owner: 2 },
        { id: 3, users: [3, 4, 5], owner: 5 }
    ]
};

var users = state.users;
var chats = state.chats;

chats = chats.map(function each(chat) {
    // this replace the chat.users array and doesn't touch or hard code any other property
    chat.users = chat.users.map(function (id) {
        return users.find(function (user) {
            return user.id == id;
        }).name;
    });

    return chat;
});

console.log(chats);
document.write('<pre>' + JSON.stringify(chats, null, 3) + '</pre>');
&#13;
&#13;
&#13;