在Javascript中将对象数组转换为数组

时间:2017-12-22 11:44:03

标签: javascript

我有以下JSON数组

var myObj = [{
  1: ['one'],
  2: ['two'],
  3: ['three']
}];

我想将其转换为如下所示的数组

['one', 'two', 'three'] 

5 个答案:

答案 0 :(得分:1)

在jquery中执行此操作的一种方法 -



var myObj = [{
  1: ['one'],
  2: ['two'],
  3: ['three']
}];

var res = [];
$.each(myObj[0], function(index, value) {
  res.push(value[0]);
});

console.log(res);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

请记住,对象键没有保证顺序,我得到所有条目,在索引上对它们进行排序,然后将它们映射到它们值的第一个索引。

&#13;
&#13;
var myObj = [{
  1: ['one'],
  2: ['two'],
  3: ['three']
}];

var myArr = Object.entries(myObj[0])
  .sort(([k1, _], [k2, __]) => k1 - k2)
  .map(([_, [v]]) => v);

console.log(myArr);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

Object.keys(myObj[0]).map(item => myObj[0][item][0])

答案 3 :(得分:0)

虽然带有串行整数的对象键按其值排序,但您可以只取值并连接数组。

&#13;
&#13;
var array = [{ 3: ['three'], 1: ['one'], 2: ['two'] }],
    result = array.reduce((r, o) => r.concat(...Object.values(o).map(([a]) => a)), []);
    
console.log(result);
&#13;
&#13;
&#13;

答案 4 :(得分:0)

Scarface Embroidered Leather




//Sca???rfa???ce??? E???mbr???oi�d???ered L�e???athe
//Scarface Embroidered Leathe

String hex="5363613f3f3f7266613f3f3f63653f3f3f20453f3f3f6d62723f3f3f6f69‌​643f3f3f65726564204c‌​653f3f3f61746865";
byte[] bytes= hexStringToBytes(hex);

//the only line you need
String res = new String(bytes,"UTF-8").replaceAll("\\\u003f","").replaceAll('�',"").replaceAll("�","");

private static byte charToByte(char c) {
    return (byte) "0123456789ABCDEF".indexOf(new String(c));
}


public static byte[] hexStringToBytes(String hexString) {
    if (hexString == null || hexString.equals("")) {
        return null;
    }
    hexString = hexString.toUpperCase();
    int length = hexString.length() / 2;
    char[] hexChars = hexString.toCharArray();
    byte[] d = new byte[length];
    for (int i = 0; i < length; i++) {
        int pos = i * 2;
        d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));

    }
    return d;
}

public static String bytesToHexString(byte[] src){
    StringBuilder stringBuilder = new StringBuilder("");
    if (src == null || src.length <= 0) {
        return null;
    }
    for (int i = 0; i < src.length; i++) {
        int v = src[i] & 0xFF;
        String hv = Integer.toHexString(v);
        if (hv.length() < 2) {
            stringBuilder.append(0);
        }
        stringBuilder.append(hv);
    }
    return stringBuilder.toString();
}

public   String printHexString( byte[] b) {
    String a = "";
    for (int i = 0; i < b.length; i++) { 
        String hex = Integer.toHexString(b[i] & 0xFF); 
        if (hex.length() == 1) { 
            hex = '0' + hex; 
        }

        a = a+hex;
    } 

    return a;
}
  

如果您的对象参数已编号,您可以这样做,如果没有尝试将其排列为某种顺序,那么您可以循环它

希望它有效