如果元素在角度匹配另一个数组时如何推入数组的元素?

时间:2019-11-21 12:05:47

标签: angular typescript angular8

我有以下数组,

array1 = [{"index":1,"firstname":"John","lastname":"Cruiser","phoneNumber":765758757},{"index":2,"firstname":"Carl","lastname":"Turner","phoneNumber":123432434},{"index":1,"firstname":"Anna","lastname":"Mull","phoneNumber":23434455}]

array2 = [{"field":"index","header":"INDEX"},{"field":"firstname","header":"FIRSTNAME"},{"field":"lastname","header":"LASTNAME"}]

现在,我想将array1的数据推入新数组中,但我不想将所有列都添加到新数组中,我只想添加array2中可用的那些字段。

array3的输出应如下所示,

array3 = [{"INDEX":1, "FIRSTNAME":"John","LASTNAME":"Cruiser" },{"INDEX":2,"FIRSTNAME":"Carl","LASTNAME":"Turner"},{"INDEX":1,"FIRSTNAME":"Anna","LASTNAME":"Mull"}]

我试图做这样的事情,

array2.forEach(element => {
array3.push(array1[element.field]);
})

但是,这无法正常工作,有人可以帮助我吗,谢谢您的帮助。

谢谢!

5 个答案:

答案 0 :(得分:1)

您可以建立十字路口:

让路口= arrA.filter(x => arrB.includes(x));

您的情况:

let array3 = array1.filter(x => array2.includes(x));

与破折号的交集:

const _ = require("lodash")
var a = { 'a': 1, 'b': 2, 'c': 3 };
var b = { 'c': 3, 'd': 4, 'e': 5 };

_.intersection(_.keys(a), _.keys(b)); // ['c']

答案 1 :(得分:1)

array2.forEach(element => {
   array1.forEach(e => {
       array3.push(e[element.field]);
   }
})

答案 2 :(得分:1)

var array1 = [{
  "index": 1,
  "firstname": "John",
  "lastname": "Cruiser",
  "phoneNumber": 765758757
}, {
  "index": 2,
  "firstname": "Carl",
  "lastname": "Turner",
  "phoneNumber": 123432434
}, {
  "index": 1,
  "firstname": "Anna",
  "lastname": "Mull",
  "phoneNumber": 23434455
}]

var array2 = [{
  "field": "index",
  "header": "INDEX"
}, {
  "field": "firstname",
  "header": "FIRSTNAME"
}, {
  "field": "lastname",
  "header": "LASTNAME"
}];

var array3 = [];


array1.forEach(value => {
  var hasAnyField = false;
  var temp = {}; 
  array2.forEach(fieldDef => { //iterate through for each field definition

    var target = value[fieldDef.field];
    if (target) { // field located
      hasAnyField = true; // it has at least 1 field
      temp[fieldDef.header] = target; // set the header
    }
  });

  if (hasAnyField) { // if has any field we will have a valid object then
    array3.push(temp);
  }

});

console.log(array3);

答案 3 :(得分:1)

一种破破烂烂的方式:

const array1 = [{"index":1,"firstname":"John","lastname":"Cruiser","phoneNumber":765758757},{"index":2,"firstname":"Carl","lastname":"Turner","phoneNumber":123432434},{"index":1,"firstname":"Anna","lastname":"Mull","phoneNumber":23434455}];

const array2 = [{"field":"index","header":"INDEX"},{"field":"firstname","header":"FIRSTNAME"},{"field":"lastname","header":"LASTNAME"}];


const fields = array2.map(field => field.field);

const array3 = array1.map(e => _pick(e, fields));

console.log(array3);

Stackblitz:https://stackblitz.com/edit/angular-aq8tua

答案 4 :(得分:1)

您只需使用下面的代码即可实现所需的结果,而无需使用任何库。

dist