簡體   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