繁体   English   中英

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

[英]creating custom array from existing array in javascript

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

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

请帮忙。

这不是你所要求的,但仍然尝试这种方法。

您基本上想通过键“代码”对数组执行“加入”操作,因此可以尝试将数组转换为map对象 - key: code , value : {name1, name2}

提琴手

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" }]
*/

像这样的东西?

您可以使用 reduce 或 map ,但在我看来,这对于一个简单的任务来说更容易理解

我假设搜索是按代码排序的。

 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"} ], finald = []; finald.push(search[0]); for (var i = 1; i < search.length; i++) { var f = finald[finald.length - 1]; if (f.code == search[i].code) { f.name1 += ","+search[i].name1; f.name2 += ","+search[i].name2; } else { finald.push(search[i]); } } console.log(finald);

这应该做你想做的:

 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 items = search.reduce((acc, item) => { const code = item.code; if (!acc[code]) acc[code] = {name1: [], name2: []}; acc[code].name1.push(item.name1); acc[code].name2.push(item.name2); return acc; }, {}); const finald = Object.keys(items).reduce((acc, key) => { const item = items[key]; acc.push({ code: key, name1: item.name1.join(','), name2: item.name2.join(',') }); return acc; }, []);

您可以为此创建自己的自定义逻辑:

 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" }, ]; //this is the result array var result = []; //this is a flag var itemExist = false; search.forEach((item) => { //reset flag to false itemExist = false; //check if the object already exist in the result array or not for(var i=0; i<result.length; i++){ //if the object exist then merge the values of name1 and name2 if(result[i].code === item.code){ result[i].name1 = result[i].name1 +','+item.name1; result[i].name2 = result[i].name2 +','+item.name2; itemExist = true; //break the for loop break; } } //if object do not exist in the result array then push it if(!itemExist){ result.push(item); } }); console.log(result);

我写了这个函数:

function normalize(arr) {
    var output = [];
      for(var i = 0; i < arr.length; i++) {
        var codeIndex = _findIndex(output, arr[i].code);
        if(codeIndex !== -1) {
          // Code already in output array, merge names.
          output[_findIndex(output, arr[i].code)].name1 += ', ' + arr[i].name1;
          output[_findIndex(arr[i].code)].name2 += ', ' + arr[i].name2;
        }
        else {
          // Code new to output array, pus into.
          output.push(arr[i]);
        }
      }

      return output;

      //
      // Privates
      //

      function _findIndex(arr, code){
        var index = -1;
        for(var i = 0; i < arr.length; i++){
          if(arr[i].code == code) {
            index = i;
            break;
          }
        }
        return index;
      }
    }

输出:

0 : {code: "t1", name1: "n1, n5", name2: "n2, n6, n20"}
1 : {code: "t2", name1: "n10, n18", name2: "n11"}
2 : {code: "t3", name1: "n18", name2: "n20"}

您可以使用reducemap

 let 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"},]; let result = Object.values( search.reduce( (c,v) => { c[ v.code ] ? c[ v.code ].push( v ) : c[ v.code ] =[ v ]; return c; },{}) ).map( v => { let n1 = [], n2 = []; v.forEach( e => { n1.push( e.name1 ); n2.push( e.name2 ); }); return { code : v[0].code, name1 : n1.join(","), name2 : n2.join(",") } }); console.log( result );

另一个解决问题的方法 - 这段代码强调数据的不变性,从所有迭代中返回新对象。 这可能会防止在执行此类操作时难以发现错误:

 var finald = transform([ { 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" }, ]); console.log(finald); function transform(source) { const keyedByCode = source.reduce((acc, item) => { const { name1 = [], name2 = [] } = acc[item.code] || {}; return Object.assign({}, acc, { [item.code]: { name1: [item.name1, ...name1], name2: [item.name2, ...name2], }, }); }, {}); return Object.keys(keyedByCode).map((code) => ({ code, name1: keyedByCode[code].name1.sort().join(','), name2: keyedByCode[code].name2.sort().join(','), })); }
 .as-console-wrapper { max-height: 100% !important; }

代码的顺序在这里无关紧要:

 const 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"}]; function combineObjectsByCode(objects) { let codes = new Set(); objects.forEach(object => codes.add(object.code)); let combinedObjects = []; codes.forEach(code => { let objectsWithSameCode = objects.filter(object => object.code === code); let combinedObject; objectsWithSameCode.forEach( obj => { if (!combinedObject) { combinedObject = obj; } else { combinedObject.name1 = combinedObject.name1 + ', ' + obj.name1; combinedObject.name2 = combinedObject.name2 + ', ' + obj.name2; } }) combinedObjects.push(combinedObject); }); return combinedObjects; } console.log(combineObjectsByCode(search));

您可以使用array#reduce根据code对数组进行分组,并将相同的值推送到数组中。 使用Object.values()获取所有值,然后使用array#map使用array#join()将数组转换为字符串。

 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" }], result = Object.values(search.reduce((r,{code,name1, name2}) => { r[code] = r[code] || {code, name1: [], name2: []}; r[code].name1.push(name1); r[code].name2.push(name2); return r; },{})) .map(({code,name1,name2}) => ({code, name1: name1.join(','), name2: name2.join(',')})); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM