Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to extend and merge two arrays containing objects

agershun edited this pageDec 28, 2014 ·1 revision

How to extend and merge two arrays containing objects?

Source:StackOverflow.com

Question

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:

  1. thelocation values have been taken fromarrB, notarrA,
  2. thatnewArr's objects now containhref keys, taken fromarrA.

Values should be from the second array, but new keys are maintained from the first array.

Answer

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 examplesat jsFiddle

© 2014-2026,Andrey Gershun &Mathias Rangel Wulff

Please help improve the documentation by opening a PR on thewiki repo

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp