简体   繁体   English

将键值对的JSON数组转换为Javascript中的JSON字符串数组

[英]convert JSON array of key value pairs to JSON Array of strings in Javascript

so i have a JSON Object [{"key1":"val1","key2":"val2"},{"key1":"val1","key2":"val2"}] 所以我有一个JSON对象[{"key1":"val1","key2":"val2"},{"key1":"val1","key2":"val2"}]

and i essentially need to remove the keys so the output looks like [["val1","val2"],["val1","val2"]] in Javascript. 我基本上需要删除键,以便输出看起来像Javascript中的[["val1","val2"],["val1","val2"]]

short of iterating through the array and then iterating through all the properties and mapping to a new JSON object is there any way i can remove the keys from the object, and turn the values in to a list in an array? 除了遍历数组然后遍历所有属性并映射到新的JSON对象之外,还有什么方法可以从对象中删除键,然后将值转换为数组中的列表?

please no string splicing/ regex. 请不要使用字符串拼接/正则表达式。

Thanks. 谢谢。

Using ES2015 (ES6) 使用ES2015(ES6)

const arr = [{"key1":"val1","key2":"val2"},{"key1":"val1","key2":"val2"}]
arr.map(o => Object.values(o));

See 看到

If you still need old browser support--pre ES6 如果您仍然需要旧的浏览器支持-ES6之前的版本

 var arr = [{"key1":"val1","key2":"val2"},{"key1":"val1","key2":"val2"}]; arr = arr.map(function(o){ var a = []; for(var i in o){ a.push(o[i]) } return a; }); console.log(arr); 

Plain ES5 with Array#map 带有Array#map普通ES5

 var array = [{ key1: "val1", key2: "val2" },{ key1: "val1", key2: "val2" }], mapped = array.map(function (o) { return Object.keys(o).map(function (k) { return o[k]; }); }); console.log(mapped); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You need to loop over the object and make new arrays. 您需要遍历对象并创建新数组。

for (var i = 0; i < yourobject.length; i++) {
    var myArray = [];
    for (var key in yourobject) {
         myArray.push(yourobject[key]
    }
    console.log(myArray)
}

This should do it: 应该这样做:

const arr = [{"key1":"val1","key2":"val2"},{"key1":"val1","key2":"val2"}];

const newArr = arr.map(obj => Object.values(obj));

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

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