简体   繁体   English

将对象转换为数组的最佳方法

[英]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. 我想将它转换为数组["b", "a", "r"]然后转换为字符串"bar" ,这是我的最终目标。 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. 很有可能使用Array.from(loader) ,但不幸的是Array.from期望length属性存在,我没有。

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. 我可以自由使用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 使用Object.keysfiltermapjoin

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. 使用isNaN只获取那些数字。 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 . sort将在输出数组中对您的keys进行sort ,然后通过该键访问,您可以通过reduce或只使用map然后join来从loader对象获取值。

 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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