在javascript中将JSON对象转换为数组数组

时间:2018-12-20 03:22:14

标签: javascript node.js json multidimensional-array javascript-objects

我试图从JSON对象中获取键的特定数组值,并将其存储在如下所示的数组中。

示例:

var obj = { "1":{"class":2,"percent":0.99,"box":[0.2,0.3,0.4,0.5]},
            "2":{"class":2,"percent":0.99,"box":[0.12,0.23,0.45,0.56]},
            "3":{"class":2,"percent":0.99,"box":[0.52,0.83,0.34,0.59]}
           } 

以此类推

现在,我需要获取键“ box”的值并存储在数组中。

var list = []
list = [[0.2,0.3,0.4,0.5],[0.12,0.23,0.45,0.56],[0.52,0.83,0.34,0.59]]

但是,我尝试了多种方法将数组存储在数组中,但是当我打印列表时,我能够得到这样的信息

list = 0.2,0.3,0.4,0.5,0.12,0.23,0.45,0.56,0.52,0.83,0.34,0.59

3 个答案:

答案 0 :(得分:5)

您可以将Object.keys(返回json的所有键的数组)与数组的映射结合使用,以将json转换为新数组:

const boxes = Object.keys(obj).map(key => obj[key].box)

您还可以使用Object.values,这在您的情况下实际上更好:

const boxes = Object.values(obj).map(value => value.box)

工作原理

Object.keys返回一个数组:

Object.keys(obj) // ["1", "2", "3"]

然后,您可以将它们映射到各个项目的值上:

Object.keys(obj).map(key => obj[key]) // [{box: [...]}, {box: [...]}, {box: [...]}]

然后在array.map的回调中,您仅可以返回box值:

Object.keys(obj).map(key => obj[key].box) // [[...], [...], [...]]

没有Object.keys()

function getBoxes (object) {
  var boxes = [];
  for (var key in object) {
    if (!object.hasOwnProperty(key)) continue;
    boxes.push(object[key].box);
  }
  return boxes;
}

console.log(getBoxes(obj))

for...in可以遍历对象的属性,但也可以遍历继承的属性,因此我们需要使用object.hasOwnProperty(key)来保护循环。


Object.keys():返回对象的所有可枚举属性名称的数组

Object.values():返回一个对象的所有可枚举值的数组

array.map():返回一个新数组,并在给定的回调函数中转换原始数组的每个项目

array.slice():返回原始数组的浅表副本

答案 1 :(得分:3)

尝试一下:

Object.values(obj).map(x=>x.box);

var obj = { "1":{"class":2,"percent":0.99,"box":[0.2,0.3,0.4,0.5]},
            "2":{"class":2,"percent":0.99,"box":[0.12,0.23,0.45,0.56]},
            "3":{"class":2,"percent":0.99,"box":[0.52,0.83,0.34,0.59]}
           } 
           
let list = Object.values(obj).map(x=>x.box);

console.log(JSON.stringify(list))

Object.values返回obj值的数组,然后我们使用map遍历该值(我们使用arrow function)并使用框值创建新数组。

答案 2 :(得分:2)

检查下一个示例:

1)首先,使用Object.keys()获取带有对象键的数组。

2)其次,在每个key上循环并访问与每个键关联的对象的box属性,然后将此box属性推入新数组。

var obj = {
    "1": {"class":2, "percent":0.99, "box":[0.2,0.3,0.4,0.5]},
    "2": {"class":2, "percent":0.99, "box":[0.12,0.23,0.45,0.56]},
    "3": {"class":2, "percent":0.99, "box":[0.52,0.83,0.34,0.59]}
};

var arrayOfArrays = [];

Object.keys(obj).forEach(function(k){
    arrayOfArrays.push(obj[k].box);
});

console.log(arrayOfArrays);

这里(只是为了好玩)是使用reduce()方法的另一种选择:

var obj = {
    "1": {"class":2, "percent":0.99, "box":[0.2,0.3,0.4,0.5]},
    "2": {"class":2, "percent":0.99, "box":[0.12,0.23,0.45,0.56]},
    "3": {"class":2, "percent":0.99, "box":[0.52,0.83,0.34,0.59]}
};

const reducer = (accumulator, currVal) => {
    accumulator.push(currVal.box);
    return accumulator;
};

arrayOfArrays = Object.values(obj).reduce(reducer, []);

console.log(arrayOfArrays);