简体   繁体   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. 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. When I need to, for example, push new data to the array inside there, what would be the best course of action if any at all?例如,当我需要将新数据推送到那里的数组时,如果有的话,最好的做法是什么? As per now the Map key/value elements are in this format:目前 Map 键/值元素采用以下格式:


   'someUserID', // Key

     // Value as object under here:

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

If I want to push new elements to the posts field do I have to do an Arrayfrom the whole key/value pair, do the push to where I need and then use.set to bring the modification back inside the Map object?如果我想将新元素推送到帖子字段,我是否必须从整个键/值对执行 Array,推送到我需要的位置,然后使用.set 将修改带回 Map object 内? Is there any clever way to do this?有什么聪明的方法可以做到这一点吗?

Thanks in advance, (Yes. I'm quite the beginner when it comes to this..: :) )在此先感谢,(是的。在这方面我是初学者..::))

I see you mention "Map", as in the ES6 Map object.我看到你提到“地图”,如 ES6 Map object。 I don't see why you need to use Map, a simple JS object should suffice.我不明白你为什么需要使用 Map,一个简单的 JS object 就足够了。

Here's an example of manipulating arrays in a simple JS object,这是一个在简单的 JS object 中操作 arrays 的示例,

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

Similarly, here's an example of manipulating objects in a simple JS object,同样,这里是一个在简单的 JS object 中操作对象的例子,

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

If you insist on using ES6 Map then here is the same example for that,如果你坚持使用 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")

You can get the value using the userId key and the value returned can be pushed just like a normal array您可以使用 userId 键获取值,并且可以像普通数组一样推送返回的值

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

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