-1

I have 2 Arrays.

I want to merge the Field Values from 2nd Array with the 1st Array.

Every value (i.e. "Test") belongs to the Profile Field id listed in the _embedded part of 2nd Array (_embedded.profileField.id).

1st Array: Profile Fields

0: Object
field: "FieldLabel1"
id: 1

1: Object
field: "FieldLabel2"
id: 7

2: Object
field: "FieldLabel3"
id: 12

2nd Array: Profile Field Values

0: Object
id: 1
value: "Test"
_embedded: Object
  profileField: Object
    field: "FieldLabel1"
    id: 1

1: Object
id: 2
value: "links"
_embedded: Object
  profileField: Object
    field: "FieldLabel2"
    id: 7

How can I get one Array with both informations together?

Swaraj Giri
  • 4,007
  • 2
  • 27
  • 44
Simon Hagmann
  • 141
  • 1
  • 12

2 Answers2

0

Using map and filter from Array methods U can merge this arrays with condition you need. Please see following examples:

/* your arrays definition */
var a = [{
  field: "FieldLabel1",
  id: 1
}, {
 field: "FieldLabel2",
 id: 7
}, {
  field: "FieldLabel3",
  id: 12
}
];

var b = [{
  id: 1,
  value: "Test",
  _embedded: {
  profileField: {
      field: "FieldLabel1",
      id: 1
    }
  }
}, {
  id: 2,
  value: "links",
  _embedded: {
  profileField: {
      field: "FieldLabel2",
      id: 7
    }
  }
}];

/* mergedArray contains merged data from two arrays arranged by id */ 
var mergedArray = a.map(function(aItem){ 
  var value = b.filter(function(bItem) {
    return aItem.id === bItem._embedded.profileField.id;
  }).map(function(item){
    return item.value;
  }).pop();
  aItem.value = value;
  return aItem; 
});

the result is:

margedArray: Array[3]
0: Object
    field: "FieldLabel1"
    id: 1
    value: "Test"
1: Object
    field: "FieldLabel2"
    id: 7
    value: "links"
2: Object
   field: "FieldLabel3"
   id: 12
   value: undefined
Vasyl
  • 1,393
  • 15
  • 26
-1

Hi Simply use Jquery see below code!

For Array:

var newArray = $.merge(1Array, 2Array);

For Object:

var object = $.extend({}, object1, object2);

For array: jquery merge array

For Object: jquery merge object

Thanks

Vinod Patidar
  • 685
  • 4
  • 17
  • $.merge is jQueery's bloated array.concat - `$.merge(Array1, Array2)` is not much more than `Array1 = Array1.concat(Array2)` done at 1/10th the speed and 10 times the memory – Jaromanda X Sep 23 '15 at 09:12
  • You think it is not your solution let me remove that answer. – Vinod Patidar Sep 23 '15 at 09:14