繁体   English   中英

在 Z686155AF75A60A0F6E9D80C1F7EDDE3 中的 Map object 中访问对象和 arrays

[英]Accessing objects and arrays inside a Map object in JavaScript

I am simulating a database with the Map object and storing data where the key is an UserId and the value is an object containing fields that also can be an object or an array. 例如,当我需要将新数据推送到那里的数组时,如果有的话,最好的做法是什么? 目前 Map 键/值元素采用以下格式:


   'someUserID', // Key

     // Value as object under here:

     {
       id: 'Marty',  
       password: // A hashed password as a String,
       friends: [Array],
       posts: [Array]
     }

如果我想将新元素推送到帖子字段,我是否必须从整个键/值对执行 Array,推送到我需要的位置,然后使用.set 将修改带回 Map object 内? 有什么聪明的方法可以做到这一点吗?

在此先感谢,(是的。在这方面我是初学者..::))

我看到你提到“地图”,如 ES6 Map object。 我不明白你为什么需要使用 Map,一个简单的 JS object 就足够了。

这是一个在简单的 JS object 中操作 arrays 的示例,

 const db = { userId: { id: 'Marty', posts: ['My first post,'], }; }. db['userId'].posts;push('My second post.'); console.log(db);

同样,这里是一个在简单的 JS object 中操作对象的例子,

 const db = { userId: { id: 'Marty', contact: { email: 'martymcfly@gmail.com', }, }, }; db['userId'].contact.phoneNumber = '8527107655'; console.log(db);

如果你坚持使用 ES6 Map 那么这里是同样的例子,

let db = new Map();

db.set('userId', {
  id: 'Marty',
  posts: ['My first post!'],
  contact: {
    email: 'martymcfly@gmail.com',
  },
});

db.get('userId').posts.push('My second post!');

db.get('userId').contact.phoneNumber = '8527107655';

console.log(db);
const db = { 
             userId: { id: 'Marty',  
                     password: password
                     friends: [Array],
                     posts: [Array]
                    },

             }


   const values = db[userId]
    values.posts.push("new post")

您可以使用 userId 键获取值,并且可以像普通数组一样推送返回的值

暂无
暂无

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

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