简体   繁体   中英

Best way to convert object into array

I have an object literal of following syntax:

const loader = {
    "0": "b",
    "1": "a",
    "2": "r",
    // arbitrary extra fields:
    "foo": 123,
    "quux": 456,
}

I want to convert it into array ["b", "a", "r"] and then into string "bar" , which is my final goal. I don't need any extra fields, if any, and can safely discard them.

It was tempting to use Array.from(loader) , yet unfortunately Array.from expects length attribute to be present, which I don't have.

Given that object literal key order is not guaranteed in my case, this is the cleanest solution I've came up with so far:

function convert(obj) {
    const a = [];
    for (const k in obj) {
        a[k] = obj[k];
    }
    return a.join('');
}

Though I don't like it and it seems rather redundant and inelegant for me. Is there anything I might miss? I'm free to use anything from ES6.

You could convert an array of the object and take joined values as string.

 var loader = { 0: "b", 1: "a", 2: "r", foo: 123, quux: 456 }, string = Object.assign([], loader).join(''); console.log(string); 

Use Object.keys , filter , map and join

var output = Object.keys( loader ) //get the keys
              .filter( s => !isNaN( s ) ) //remove non-numeric keys
              .map( s => loader[s] ) //get values for filtered keys
              .join( "" ); //join them

If the keys needs to be sorted explicitly, then

var output = Object.keys( loader ) //get the keys
              .filter( s => !isNaN( s ) ) //remove non-numeric keys
              .sort( ( a, b ) => a - b );
              .map( s => loader[s] ) //get values for filtered keys
              .join( "" ); //join them

Using isNaN gets only those ones, that are numbers. sort will order your keys in the output array and then accessing via that keys you can get the values from the loader object via reduce or just use map and then join .

 const loader = { "0": "b", "1": "a", "2": "r", // arbitrary extra fields: "foo": 123, "quux": 456, }; const obj = Object.keys(loader).filter(key => !isNaN(key)) .sort() .map(key => loader[key]) .join(''); console.log(obj); 

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