对象过滤器某些值

时间:2019-08-01 10:35:19

标签: javascript object

我有这个JSON对象:

{
    "active":     0,
    "0":          "active",
    "inactive":   1,
    "1":          "inactive",
    "ineligable": 2,
    "2":          "ineligable",
    "error":      3,
    "3":          "error",
    "suspended":  4,
    "4":          "suspended",
    "archived":   5,
    "5":          "archived",
    "removed":    6,
    "6":          "removed"
}

我想用一个数值过滤那些。事情是我已经做到了。但是以一种非常丑陋的方式,我想知道是否有比我做的更好的方法来过滤对象。

这是我的尝试:

const statuses = listingstatus; //this is the object

let toFill = [];
Object.keys(statuses).forEach(key => {
    if(Number.isInteger(statuses[key])){
        toFill.push({[key]: statuses[key]});
    };

});

console.log(toFill)

结果是这样

Array:

0: {active: 0}
1: {inactive: 1}
2: {ineligable: 2}
3: {error: 3}
4: {suspended: 4}
5: {archived: 5}
6: {removed: 6}

3 个答案:

答案 0 :(得分:2)

为了仍然满足您的要求,您可以使用Object.entries代替Object.keys来简化它,并使用Object.reduce将结果减小为单个值,而不是在必要时迭代并推入另一个变量

const statuses = {
  "active": 0,
  "0": "active",
  "inactive": 1,
  "1": "inactive",
  "ineligable": 2,
  "2": "ineligable",
  "error": 3,
  "3": "error",
  "suspended": 4,
  "4": "suspended",
  "archived": 5,
  "5": "archived",
  "removed": 6,
  "6": "removed"
}

const toFill = Object.entries(statuses).reduce((all, [key, value]) => Number.isInteger(value) ? [...all, {[key]:value}] : all,[]);

console.log(toFill)

但是,我想知道为什么首先需要这样的格式,我认为最好只返回带有这些值的单个对象,而不是对象数组,在这种情况下,您应该执行以下操作:

const statuses = {
  "active": 0,
  "0": "active",
  "inactive": 1,
  "1": "inactive",
  "ineligable": 2,
  "2": "ineligable",
  "error": 3,
  "3": "error",
  "suspended": 4,
  "4": "suspended",
  "archived": 5,
  "5": "archived",
  "removed": 6,
  "6": "removed"
}

const toFill = Object.entries(statuses).reduce((all, [key, value]) => Number.isInteger(value) ? {...all, [key]:value} : all,{});

console.log(toFill)

答案 1 :(得分:0)

尝试一下,我用过Object.keysArray.reduce

const obj = {
  "active": 0,
  "0": "active",
  "inactive": 1,
  "1": "inactive",
  "ineligable": 2,
  "2": "ineligable",
  "error": 3,
  "3": "error",
  "suspended": 4,
  "4": "suspended",
  "archived": 5,
  "5": "archived",
  "removed": 6,
  "6": "removed"
};

const output = Object.keys(obj).reduce((acc, k) => Number.isInteger(obj[k]) ? (acc.push({ [k]: obj[k] }), acc) : acc, []);

console.log(output);

答案 2 :(得分:0)

您可以尝试这种方式:

match $a1 "hello world"; ($a1, $a2) isa parenthetical-alarm-name; get;