我有一个json文件,看起来像这样
[
{
path1:"xyz",
path2: "xyz2",
file1: "filea",
file2: "fileb",
state: "equal"
},
{
path1:"xyz",
path2: "xyz2",
file1: "filec",
file2: "filed",
state: "distinct"
},
{
path1:"xyz",
path2: "xyz2",
file1: "filee",
file2: "filef",
state: "equal"
},
{
path1:"xyz4",
path2: "xyz3",
file1: "fileg",
file2: "fileh",
state: "distinct"
}
]
问题是我应该得到json对象数据的类型为state:distinct
应该像这样
[
{
path1:"xyz",
path2: "xyz2",
file1: "filec",
file2: "filed",
state: "distinct"
},
{
path1:"xyz4",
path2: "xyz3",
file1: "fileg",
file2: "fileh",
state: "distinct"
}
]
是否有任何解决方案,这样,我可以得到json数据像上面的JavaScript?
const data = [
{
path1:"xyz",
path2: "xyz2",
file1: "filea",
file2: "fileb",
state: "equal"
},
{
path1:"xyz",
path2: "xyz2",
file1: "filec",
file2: "filed",
state: "distinct"
},
{
path1:"xyz",
path2: "xyz2",
file1: "filee",
file2: "filef",
state: "equal"
},
{
path1:"xyz4",
path2: "xyz3",
file1: "fileg",
file2: "fileh",
state: "distinct"
}
]
const result = data.filter((item) => item.state === 'distinct');
console.log(result)
首先,您共享的数据不是json。它看起来像一个普通的js数组。其次,如果你想转换为json,你可以使用json. stringify()方法,但是对于这个方法,你共享的格式或从该数据派生的以下函数的输出将不会是一个有效的json。
function filterData (data, key, value) {
return data.filter((item) => item[key] === value )
}
const filteredData = filterData(data, 'state', 'distinct')
如果您使用Lodash(https://www.npmjs.com/package/lodash)或下划线包,那么它非常简单,您可以在一行中完成。
enter code here
var data = [
{
path1:"xyz",
path2: "xyz2",
file1: "filea",
file2: "fileb",
state: "equal"
},
{
path1:"xyz",
path2: "xyz2",
file1: "filec",
file2: "filed",
state: "distinct"
},
{
path1:"xyz",
path2: "xyz2",
file1: "filee",
file2: "filef",
state: "equal"
},
{
path1:"xyz4",
path2: "xyz3",
file1: "fileg",
file2: "fileh",
state: "distinct"
}
];
var distinctStates = _.filter(data, { 'state': 'distinct'});
我希望它能帮助你。
可以使用Array
的filter()
方法
这是你想要的吗?Array.prototype.filter ()
const datas = [
{
path1:"xyz",
path2: "xyz2",
file1: "filea",
file2: "fileb",
state: "equal"
},
{
path1:"xyz",
path2: "xyz2",
file1: "filec",
file2: "filed",
state: "distinct"
},
{
path1:"xyz",
path2: "xyz2",
file1: "filee",
file2: "filef",
state: "equal"
},
{
path1:"xyz4",
path2: "xyz3",
file1: "fileg",
file2: "fileh",
state: "distinct"
}
];
const distincts = datas.filter(data => data.state === 'distinct');
使用filter()方法获取状态为distinct的JSON对象数据
filter()方法创建一个新的数组,其中包含通过函数提供的测试的元素。
const myJson = [
{
path1: "xyz",
path2: "xyz2",
file1: "filea",
file2: "fileb",
state: "equal",
},
{
path1: "xyz",
path2: "xyz2",
file1: "filec",
file2: "filed",
state: "distinct",
},
{
path1: "xyz",
path2: "xyz2",
file1: "filee",
file2: "filef",
state: "equal",
},
{
path1: "xyz4",
path2: "xyz3",
file1: "fileg",
file2: "fileh",
state: "distinct",
},
];
const result = myJson.filter((item) => item.state === "distinct");
console.log(result);