简体   繁体   中英

Passing object key name in function parameter

I want to pass key (mykey) in parameter like below

var dat =   sortMe(array,"mykey");

to function like this

function sortMe(data,customname)
{
 sorted = Object.assign(...Object
        .entries(data)
        .sort(({ 1: { customname: a } }, { 1: { customname: b } }) => a - b)
        .map(([k, v]) => ({ [k]: v }))
    );

return sorted;
}

Above code does not work , but if works only when I use the key name directly in function name like below

function sortMe(data,customname)
{
 sorted = Object.assign(...Object
        .entries(data)
        .sort(({ 1: { mykey : a } }, { 1: { mykey: b } }) => a - b)
        .map(([k, v]) => ({ [k]: v }))
    );

return sorted;
}

What you're trying to do can be achieved with a computed property name :

{ [name]: value }

So, change this line:

.sort(({ 1: { customname: a } }, { 1: { customname: b } }) => a - b)

to:

.sort(({ 1: { [customname]: a } }, { 1: { [customname]: b } }) => a - b)

try using:

function sortMe(data,customname)
{
 sorted = Object.assign(...Object
        .entries(data)
        .sort(({ 1: { `${customname}`: a } }, { 1: { `${customname}`: b } }) => a - b)
        .map(([k, v]) => ({ [k]: v }))
    );

return sorted;
}

Hope this helps.

This is opinion, but using object destructuring for this just seems really quite unreadable and difficult, not to mention being considerably longer than doing it the normal way.

Also, you can use Object.fromEntries instead of needing two additional iterations to transform and spread the entries array.

See here:

function sortMe(data,key)
{
    return Object.fromEntries(Object
        .entries(data)
        .sort((a,b) => a[1][key] - b[1][key])
    );
}

How about first sorting the copy of the array, then transform it with the Object.entries.

Note that the sort doesn't use the a - b (which is more used for numbers in strings)

Example snippet:

 let data = [ { id: 2, name: "john"}, { id: 3, name: "bob"}, { id: 4, name: "anna"}, { id: 1, name: "jane"} ]; function sortMe(data, key) { return Object.entries( [...data].sort((a,b) => a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0) ); } console.log('sorted by name', JSON.stringify(sortMe(data,'name'))); console.log('sorted by id', JSON.stringify(sortMe(data,'id'))); console.log('unsorted data', JSON.stringify(data));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM