gpt4 book ai didi

javascript - 根据属性值分隔值并使用 javascript 显示

转载 作者:行者123 更新时间:2023-11-30 19:47:43 26 4
gpt4 key购买 nike

我有一个如下所示的数组:

var array = [[
{ "loc": {} },
{ "distance": 6.4 },
{ "zip1": "06120" },
{ "zip2": "06095" },
{ "group": 1 },
{ "weight": 1119 }
], [
{ "loc": {} },
{ "distance": 6.41 },
{ "zip1": "06095" },
{ "zip2": "06120" },
{ "group": 2 },
{ "weight": 41976 }
], [
{ "loc": {} },
{ "distance": 6.41 },
{ "zip1": "06095" },
{ "zip2": "06120" },
{ "group": 1 },
{ "weight": 41976 }
]];

现在我想根据属性值获取数组值以在 HTML 中显示。预期输出被拆分为具有“组”属性的数组。我还需要基于组存储在 HTML 中,如下例所示:

group 1:
all zip1's under group 1
group 2:
all zip1's under group 2

我试过使用循环,但没能得到正确的答案:

for (var k = 0; k < array.length; k++) {
var array1 = array[k];
if (flag[array1[2]["zip1"]]) continue;
flag[array1[2]["zip1"]] = true;
output2.push(array1);
}

所以帮我找到用分组方式拆分 HTML 中的数组显示

sample output

最佳答案

使用 reduce,您可以创建一个对象,每个 group 值作为键,zip1 数组作为值,如下所示:

然后遍历 Object.entries,创建 HTML:

const array = [[{"loc":{}},{"distance":6.4},{"zip1":"06120"},{"zip2":"06095"},{"group":1},{"weight":1119}],[{"loc":{}},{"distance":6.41},{"zip1":"06095"},{"zip2":"06120"},{"group":2},{"weight":41976}],[{"loc":{}},{"distance":6.41},{"zip1":"06095"},{"zip2":"06120"},{"group":1},{"weight":41976}]];

const merged = array.reduce((r, a) =>{
const { group } = a.find(n => n.group)
const { zip1 } = a.find(n => n.zip1)
r[group] = r[group] || []
r[group].push(zip1)
return r;
},{})

const output = document.getElementById('output');

Object.entries(merged).forEach(([group, zips]) => {
const h1 = document.createElement('h1');
h1.innerHTML = "group " + group

const span = document.createElement('span');
span.innerHTML = `Zip1 - ${zips} (in group - ${group})`;

output.appendChild(h1)
output.appendChild(span)
})
<div id="output"></div>

关于javascript - 根据属性值分隔值并使用 javascript 显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54802407/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com