这是我的数据集的样子:
const data = {
"VS_factor": [
"FA1_n",
"FA1_y",
"FA2_n"
],
"coord.Dim.1": [
-0.232849099744328,
0.875136458459595,
-0.0810629616429348,
],
"coord.Dim.2": [
0.0223397885030092,
-0.0839615159119212,
-0.334981738274959,
],
"cluster": [
0,
5,
0,
]
}
我想根据最后一个变量的值过滤对象和内部的每个数组。在此示例中,我只想将值保留在cluster" === 5
处。
const desired = {
"VS_factor": [
"FA1_y",
],
"coord.Dim.1": [
0.875136458459595,
],
"coord.Dim.2": [
-0.0839615159119212,
],
"cluster": [
5,
]
}
由于无法在对象上使用.filter
,因此遇到了麻烦。有人知道解决方案如何归档我想要的结果吗?
答案 0 :(得分:1)
您可以获取预期的索引,然后进行过滤
const data = {
VS_factor: ["FA1_n", "FA1_y", "FA2_n"],
"coord.Dim.1": [-0.232849099744328, 0.875136458459595, -0.0810629616429348],
"coord.Dim.2": [0.0223397885030092, -0.0839615159119212, -0.334981738274959],
cluster: [0, 5, 0],
}
const expectedIndex = data.cluster.findIndex((c) => c === 5)
const res = Object.fromEntries(
Object.entries(data).map(([key, value]) => [key, [value[expectedIndex]]])
)
console.log(res)
答案 1 :(得分:0)
假设您要过滤那些不在特定索引处的元素(在簇=== 5处的索引)。
const data = { "VS_factor": [ "FA1_n", "FA1_y", "FA2_n" ], "coord.Dim.1": [ -0.232849099744328, 0.875136458459595, -0.0810629616429348, ], "coord.Dim.2": [ 0.0223397885030092, -0.0839615159119212, -0.334981738274959, ], "cluster": [ 0, 5, 0, ] },
targetCluster = 5,
targetIndex = data.cluster.findIndex(c => c === targetCluster),
result = Object.entries(data).map(([key, array]) => ({[key]: [array[targetIndex]]}));
console.log(result);
答案 2 :(得分:0)
我将定义一个过滤器函数,该函数带有三个参数:进行过滤的键,所需的值以及数据对象
const filterData = (key, value, data) => {
const result = {}
for (let i = 0; i < data[key].length; i++) {
if (data[key][i] === value) { // found the desired Index
Object.entries(data).forEach(([dataKey, dataArr]) => {
if (!result[dataKey]) {
result[dataKey] = []
}
result[dataKey].push(dataArr[i])
})
}
}
return result
}
此功能将在不同的键上起作用,并且还将提取多个具有目标值的元素的“记录”(例如,有2个记录,cluster
等于5。
代码做出的一些假设,如果无效,请添加一些检查:
===
检查是否相等。答案 3 :(得分:0)
从集群中获取索引,检查是否找到了索引,否则返回没有数据的对象。使用此索引遍历Object.values并将新条目推送到properties-arrays。
const data = {
VS_factor: ["FA1_n", "FA1_y", "FA2_n"],
"coord.Dim.1": [-0.232849099744328, 0.875136458459595, -0.0810629616429348],
"coord.Dim.2": [0.0223397885030092, -0.0839615159119212, -0.334981738274959],
cluster: [0, 5, 0],
};
function filterClusterId(id, data) {
let ind = data.cluster.indexOf(id);
let result = {VS_factor: [], "coord.Dim.1": [], "coord.Dim.2": [], cluster: []};
if (ind===-1) return result;
Object.entries(data).forEach(([key,value]) => {
result[key].push(value[ind]);
})
return result;
}
console.log(filterClusterId(5, data));