我可以像这样连接字符串和Json属性吗?

时间:2017-07-25 10:42:02

标签: javascript arrays json

我有这样的JSON数据。

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
  }

如果我需要从JSON获取元素属性名称,我将使用Object.keys(data[0])

我会得到(4) ["purchaseId", "name", "date", "price"]

因此,当我使用Object.keys(data[0])[1]时,我的结果为name

然后我会保留var nameOfAtt = Object.keys(data[0])[1]

我需要在

中使用
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]);
        }
    }
}

所以我将得到只有Johny的数据对象

我的问题我无法使用data[i].Object.keys(data[i])[j]它显示身份不明但我可以使用data[i].name

如何连接这样的字符串。

4 个答案:

答案 0 :(得分:0)

数据应该是一个数组,你可以像这样使用filter属性:

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);

答案 1 :(得分:0)

我认为你正在寻找像这样的搜索功能

var 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
        }];

        function search(name){
            var result = [];
            data.forEach(function(obj){
                if(obj.name == name)
                    result.push(obj);
            });
            return result;
        }

        //lets search 
        var rs = search("Johny");
        console.log(rs);//output results to console log

答案 2 :(得分:0)

public interface TestServiceIface {
    default String test(String str, int flag) {
        return str;
    }
}

答案 3 :(得分:0)

修复数据后,这是一个快速的ES6示例,向您展示如何从数据中过滤掉您想要的对象。

const getObjFromKey = (data, key, value) => {
  return data.filter((obj) => obj[key] === value);
}

const result = getObjFromKey(data, 'name', 'Johny');

结果

[
  {
    "purchaseId": 2,
    "name": "Johny",
    "date": "2560-07-14",
    "work": "Navy",
    "price": 15000
  }
]

DEMO