-
Notifications
You must be signed in to change notification settings - Fork 659
How to extend and merge two arrays containing objects
agershun edited this page Dec 28, 2014
·
1 revision
Source: StackOverflow.com
There is an array A:
var arrA = [{
name: 'twitter',
location: 0,
hidden: false,
href: "https://twitter.com/i/connect"
}, {
name: 'medium',
location: 1,
hidden: false,
href: "https://medium.com/me/activity"
}
];
And array B:
var arrB = [{
name: 'twitter',
location: 1,
hidden: false
}, {
name: 'medium',
location: 0,
hidden: false
}
];
How can I end up with an array that looks like this:
var newArr = [{
name: 'twitter',
location: 1,
hidden: false,
href: "https://twitter.com/i/connect"
}, {
name: 'medium',
location: 0,
hidden: false,
href: "https://medium.com/me/activity"
}
];
The algorithm is the following:
- the
location
values have been taken fromarrB
, notarrA
, - that
newArr
's objects now containhref
keys, taken fromarrA
.
Values should be from the second array, but new keys are maintained from the first array.
You can join two arrays and select proper attributes with these statements:
var res1 = alasql('SELECT arrA.name, arrB.location, arrA.href, arrB.hidden \
FROM ? arrA JOIN ? arrB USING name', [arrA,arrB]);
Or you can use ENTEND() function from standard library:
var res2 = alasql('SELECT COLUMN extend(arrA._, arrB._)
FROM ? arrA JOIN ? arrB USING name', [arrA,arrB]);
Try these examples at jsFiddle
© 2014-2024, Andrey Gershun & Mathias Rangel Wulff
Please help improve the documentation by opening a PR on the wiki repo