按键过滤对象h

时间:2017-09-28 12:31:57

标签: javascript object filter

我有一个看起来像这样的对象:

{house_id+street_id+school_id: {...}, house_id2+street_id2+school_id2: {...}, ...}

因此,对象的每个键都是一个house_id,一个street_id和一个以'+'符号分隔的school_id。

我希望能够过滤给定street_id的对象,例如,对于给定的对象:

{40+30+20: { name: "john" }, 41+31+20: { name: "eli" } }且street_id为30,返回的对象为:

{40+30+20: "john"}

我该如何进行过滤?

3 个答案:

答案 0 :(得分:0)

您可以通过以下方式执行此操作



let obj = {'40+30+20': { name: "john" }, '41+31+20': { name: "eli" } }

let result = Object.keys(obj).filter(e => e.match(/^.*\+30\+.*$/) != null).reduce((a, b) => {
    a[b] = obj[b];
    return a;
}, {});

console.log(result);




答案 1 :(得分:0)

您可以这样做:

var data = {
  '40+30+20': { 
    name: "john" 
  }, 
  '41+31+20': { 
    name: "eli" 
  } 
};

var search = '30';
var r = Object.keys(data).filter(function(key) {
  return key.split('+').some(function(p) {
    return p === search;
  });
}).map(function(key) {
  var o = {};
  o[key] = data[key];
  return o;
});

console.log(r);

答案 2 :(得分:0)

尝试使用过滤器功能和正则表达式:

var myObj = {'40+30+20': { name: "john" }, '41+31+20': { name: "eli" } };

function filterByStreet(obj, streetId) {
    var filteredKeys = Object.keys(obj).filter((key) => {
        var patt = new RegExp("[^+]+[+]" + streetId + "[+][0-9]+");
        return patt.test(key);
    });

    var outObj = {};

    for(filteredKey of filteredKeys) {
        outObj[filteredKey] = obj[filteredKey];
    }

    return outObj;
}

var filteredObj = filterByStreet(myObj, 30);
console.log(filteredObj);