按值过滤JavaScript对象

时间:2015-07-22 14:22:38

标签: javascript

我有这个对象数组:

var result = [
{
    appAddress:"127.0.0.1",
    name:"AppServer1",
    dbConnection:""
},
{
    appAdress:"",
    name:"DBServer1",
    dbConnection:"Server=.;Database=master;Integrated Security=SSPI"
}];

现在我只需要获取名称值(到数组中),其中appAddress不为空。我尝试了 array.filter() $。map(),但这些方法似乎都不是我想做的。

这是我试过的:

var appServers = $.map(result, function (val, key) {
    return (key == 'appAddress' && val.length > 0) ? key : null;
    });

var appServers = result.filter(function (entry) {
    return entry['displayName'];
    });

5 个答案:

答案 0 :(得分:2)

首先,你的对象定义是错误的。您需要使用:代替=

接下来,您可以使用简单的for循环执行此操作:

var output = [];
for (var i = 0; i < result.length; i++) {
    var item = result[i];
    if (item.appAddress) output.push(item.name);
}

Here is a working example

答案 1 :(得分:1)

你可能做的一件事是

var names = result.filter(
    function (t) {
        return t.appAddress != "";
}).map(
    function (t) {
        return t.name;
});

答案 2 :(得分:1)

你可以像这样使用reduce:

var result = [
    {
        appAdress: "127.0.0.1",
        name: "AppServer1",
        dbConnection: ""
    },
    {
        appAdress: "",
        name: "DBServer1",
        dbConnection: "Server=.;Database=master;Integrated Security=SSPI"
    }];

var addresses = result.reduce(function (acc, it) {
    if (it.appAdress) {
        acc.push(it.name);
    }
    return acc;
}, []);

console.log(addresses);
Please check the result in console.

答案 3 :(得分:1)

对于过滤,您可以使用filter的{​​{1}}和map方法。请参阅以下示例。

<强> Array.prototype.filter Docs

<强> Array.prototype.map Docs

Array
var result = [{
  appAdress: "127.0.0.1",
  name: "AppServer1",
  dbConnection: ""
}, {
  appAdress: "",
  name: "DBServer1",
  dbConnection: "Server=.;Database=master;Integrated Security=SSPI"
}];


// First Solution
var out = result.filter(function(obj) {
  return obj.appAdress;
}).map(function(obj) {
  return obj.name;
})

// Second Solution
var namesArr = [];
result.forEach(function(obj) {
  if (obj.appAdress) {
    namesArr.push(obj.name);
  }
});



document.querySelector('#out').innerHTML = JSON.stringify(out, undefined, 4);
document.querySelector('#out2').innerHTML = JSON.stringify(namesArr, undefined, 4);

答案 4 :(得分:0)

result数组中定义的对象无效。对象值写为name:value对(用冒号分隔)。

试试这个:

var result = [{
  appAdress: "127.0.0.1",
  name: "AppServer1",
  dbConnection: ""
}, {
  appAdress: "",
  name: "DBServer1",
  dbConnection: "Server=.;Database=master;Integrated Security=SSPI"
}];

var resultArr = $.map(result, function(val, i) {
  if (val.appAdress.length > 0) return val.name;
});

console.log(resultArr);
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

运行JSFiddle或详细了解jQuery.map()