Wanadjanan Klinnooch Wanadjanan Klinnooch - 3 years ago 56
Javascript Question

Can I connect string with Json attribute like this

I have JSON data like this.

data = {
"purchaseId": 1,
"name": "Rubbick",
"date": "2560-06-29",
"price": 12345.00,
},
{
"purchaseId": 2,
"name": "Johny",
"date": "2560-07-14",
"work": "Navy",
"price": 15000.00
}


if I need to get element attribute names from JSON I will use
Object.keys(data[0])
and

I will get
(4) ["purchaseId", "name", "date", "price"]


so when I used
Object.keys(data[0])[1]
my result is
name


then I will keep
var nameOfAtt = Object.keys(data[0])[1]


And I need to use in

var results = [];
var keyword = "Johny";
for(var i=0; i < data.length; i++){
for(var j=0; j < Object.keys(data[i]).length; j++){
if( data[i].Object.keys(data[i])[j] == keyword){
results.push(data[i]);
}
}
}


so I will get data object that only have Johny

My question I can't use
data[i].Object.keys(data[i])[j]
It showed unidentified but I can use
data[i].name


How can I connect string like this.

Answer Source

data should be an array and you can use filter property like this :

var attrData = ["purchaseId", "name", "date", "price"],
data = [
  {
    "purchaseId": 1,
    "name": "Rubbick",
    "date": "2560-06-29",
    "price": 12345.00,
  },
  {
    "purchaseId": 2,
    "name": "Johny",
    "date": "2560-07-14",
    "work": "Navy",
    "price": 15000.00
  }
];
var keyword = 'Johny';

var filtered = data.filter(function(dataItem){
    return dataItem[attrData[1]] === keyword;
});

console.log(filtered);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download