亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JSON 對象:從值中獲取鍵

JSON 對象:從值中獲取鍵

揚帆大魚 2023-03-03 10:05:21
好的,這是我簡化的對象:{  'aaa': {    name: 'Profile one',    created: 1587396315752,    last_save: 1599936955429,  },  'bbb': {    name: 'Profile two',    created: 1594950234265,    last_save: 1596064543536,  },  'ccc': {    name: 'Profile three',    created: 1586093327836,    last_save: 1600022533585,  }}'Profile two'例如,我的目標是讓用戶輸入配置文件的名稱,并返回相應的配置文件 ID ( 'bbb')。我嘗試了很多方法,但都沒有按預期工作。感謝您的幫助。
查看完整描述

2 回答

?
Helenr

TA貢獻1780條經驗 獲得超4個贊

您可以嘗試使用Object.entries().find()作為:

const data = { 'aaa': { name: 'Profile one', created: 1587396315752, last_save: 1599936955429, }, 'bbb': { name: 'Profile two', created: 1594950234265, last_save: 1596064543536, }, 'ccc': { name: 'Profile three', created: 1586093327836, last_save: 1600022533585, } };


const search = 'Profile two';

const result = Object.entries(data)

                     .find(([k,v]) => v.name === search)[0];


console.log(result);

從文檔中看到:

Object.entries()方法返回給定對象自己的可枚舉字符串鍵控屬性 [key, value] 對的數組,其順序與 for...in 循環提供的順序相同

find()方法返回所提供數組中滿足所提供測試函數的第一個元素的值。


查看完整回答
反對 回復 2023-03-03
?
慕神8447489

TA貢獻1780條經驗 獲得超1個贊

您可以使用Object.entries()and找到它find():


let profiles = {

  'aaa': {

    name: 'Profile one',

    created: 1587396315752,

    last_save: 1599936955429,

  },

  'bbb': {

    name: 'Profile two',

    created: 1594950234265,

    last_save: 1596064543536,

  },

  'ccc': {

    name: 'Profile three',

    created: 1586093327836,

    last_save: 1600022533585,

  }

};


let id = Object.entries(profiles).find(e => e[1].name === 'Profile two')[0];

console.log(id);


查看完整回答
反對 回復 2023-03-03
  • 2 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號