簡體   English   中英

如何從對象中獲取鍵和值並返回數組?

[英]How do I get they keys and the values from the object and return an array?

因此,讓我給您一個示例對象:

{
  example_98: value,
  example_7658: value,
  example_2764: value
  key: value,
  otherKey: otherValue
}

我想在這個對象中搜索所有example_x並返回一個看起來像這樣的數組:

[{example_98: value}, ...]

用Javascript最簡單的方法是什么? 我更喜歡純JavaScript,但是我確實可以訪問jquery,如果這樣可以更輕松。

您可以通過以下方式獲取對象的所有鍵:

var obj = {
  example_98: value,
  example_7658: value,
  example_2764: value
  key: value,
  otherKey: otherValue
}

console.log(Object.keys(obj)); // ['example_98', 'example_7658', ...]

要獲取其鍵匹配特定值的所有對象,可以執行以下操作:

var regEx = /example_/;

var onlyExamples = Object.keys(obj)
  .filter(function(o) {
    // only return keys that match regEx
    return o.test(regEx);
  })
  .map(function(o) {
    // return { key: value }
    return { o: obj(o) };
  });

這將返回包含與正則表達式匹配的值的對象數組,因此您的示例對象將返回[{example_98: value }, {example_7658: value }, {example_2764: value}]

編輯

正如@andlrc指出的那樣,您可以使用以下方法來完善您的正則表達式,使其僅選擇以“ example” 開頭的那些鍵: var regEx = /^example_/;

最簡單的方法? for-in循環

var results = [];
for (var key in obj) {
  if (key.indexOf('example_') === 0) {
    var newObj = {};
    newObj[key] = obj[key];
    results.push(newObj);
  }
}

一種更有趣/更實用的方法:

var results = Object.keys(obj)
  .filter(function(key) {
    return key.indexOf('example_') === 0;
  })
  .map(function(key) {
    var newObj = {};
    newObj[key] = obj[key];
    return newObj;
  });

先前版本的一個變體,但使用計算的名稱(在許多環境中不可用):

var results = Object.keys(obj)
  .filter((key) => key.indexOf('example_') === 0)
  .map((key) => { [key]: obj[key] });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM