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

时间:2018-02-14 12:43:03

标签: javascript arrays

我有一个如下数组:

{
    "title": "my title",
    "phone": [
        {
                    "number": 789123
                 },
                 {
                    "number": 456963
                 }
                 ]
}    

我想将此数组转换为以下格式:

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

请帮助。

9 个答案:

答案 0 :(得分:1)

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

你基本上想要通过键'代码'对数组执行'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" }]
*/

答案 1 :(得分:0)

这样的东西?

你可以使用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);

答案 2 :(得分:0)

这应该做你想要的:

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;
}, []);

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

我写了这个函数:

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"}

答案 5 :(得分:0)

您可以使用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 );

答案 6 :(得分:0)

另一个来解决问题 - 此代码强调数据的 immutability ,从所有迭代中返回新对象。这可能会阻止在执行此类操作时很难发现错误:

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

答案 7 :(得分:0)

代码的顺序在这里并不重要:

&#13;
&#13;
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));
&#13;
&#13;
&#13;

答案 8 :(得分:0)

您可以使用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);