gpt4 book ai didi

javascript - 在javascript中从现有数组创建自定义数组

转载 作者:行者123 更新时间:2023-11-30 20:45:14 25 4
gpt4 key购买 nike

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

var search = [
{ code: "t1", name1: "n1", name2: "n2" },
{ code: "t1", name1: "n5", name2: "n6" },
{ code: "t2", name1: "n10", name2: "n11" },
{ code: "t2", name1: "n18", name2: "n20" },
{ code: "t3", name1: "n18", name2: "n20" },
];

我想将这个数组转换成下面的格式:

var finald = [
{ code: "t1", name1: "n1,n5", name2: "n2,n6" },
{ code: "t2", name1: "n10,n18", name2: "11,n20" },
{ code: "t3", name1: "n18", name2: "n20" },
];

我试过如下代码。但没有成功。首先,我从数组中收集了所有唯一的 code:

var flags = [];
var codes = [];
for(var z=0; z<search.length; z++){
if( flags[data[z].code]) continue;
flags[data[z].code] = true;
codes.push(data[z].code);
}

var finald = [];
for(var i=0; i<search.length; i++){

var name1 = [];
var name2 = [];
for(var y=0; y<codes.length; y++){
if(codes[y] == search[i].code ){

var row = {
code: codes[y],
name1:search[i].name1,
name2:search[i].name2,


};
finald.push(row);
}
}
}

请帮助。

最佳答案

这不完全是您要求的,但仍然尝试这种方法。

你基本上想通过键“code”对数组执行“join”操作,所以也许尝试将你的数组转换为 map 对象 - key: code , value : {name1, name2}

jsfiddle

var search = [
{code:"t1", name1:"n1", name2:"n2"},
{code:"t1", name1:"n5", name2:"n6"},
{code:"t2", name1:"n10", name2:"n11"},
{code:"t2", name1:"n18", name2:"n20"},
{code:"t3", name1:"n18", name2:"n20"}];

const myMap = new Map();

search.forEach((obj) => {
const key = obj.code;
if(!myMap.has(key)) {
myMap.set(key, {
'name1' : obj.name1,
'name2' : obj.name2
});
} else {
var ele = myMap.get(key);
ele.name1 = `${ele.name1},${obj.name1}`;
ele.name2 = `${ele.name2},${obj.name2}`;
}
});
console.log(myMap);

/*
key: "t1" => value: {name1:"n1,n5", name2:"n2,n6"},
key: "t2" => value: {name1:"n10,n18", name2:"n11,n20"},
key: "t3" => value: {name1:"n18", name2:"n20"}
*/

如果你必须以数组形式将它添加到上面, jsfiddle

var resArray = [];
myMap.forEach((value, key) => {
resArray.push(Object.assign({'code': key}, value));
});

console.log(resArray);

/*
[{ code: "t1", name1: "n1,n5", name2: "n2,n6" },
{ code: "t2", name1: "n10,n18", name2: "11,n20" },
{ code: "t3", name1: "n18", name2: "n20" }]
*/

关于javascript - 在javascript中从现有数组创建自定义数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48787547/

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