Javascript:将强类型数组转换为JSON

时间:2018-10-19 03:02:48

标签: javascript

我有一个类别为A的数组。类别A包含2个属性,例如重量和日期。

reduce

如何将上面的数组转换为这样的内容:

$ python3 -q
>>> data_obj = { 
...     'alpha': { 
...         'bravo': [
...             {'charlie': 1}, 
...             {'delta': 2},
...         ]
...     }
... }
>>> 
>>> node_keys = ['alpha', 'bravo', 0, 'charlie']
>>> 
>>> from functools import reduce
>>> from operator import getitem
>>> 
>>> reduce(getitem, data_obj, node_keys)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str
>>> 
>>> data_obj[node_keys[0]][node_keys[1]][node_keys[2]][node_keys[3]]
1
>>> getitem(
...     getitem(
...         getitem(
...             getitem(data_obj, node_keys[0]),
...             node_keys[1]
...         ), node_keys[2]
...     ), node_keys[3]
... )
1
>>>
>>> data_obj.__getitem__(node_keys[0])\
...         .__getitem__(node_keys[1])\
...         .__getitem__(node_keys[2])\
...         .__getitem__(node_keys[3])
1
>>>

1 个答案:

答案 0 :(得分:0)

您的代码无效 JavaScript代码。我做了一些重组,在这里您有一种方法来实现所需的功能,这意味着可以用不同的方式来完成,但是由于您的代码无效,因此受到了限制。我建议仔细阅读官方文档。 MDN是一个很好的起点。我也推荐this文章。 无论如何,我希望这可以帮助您;)

// A valid JS array would look something like this:

const array = [
               {a: {Weight: 50, Date: '01/01/2009'}}, 
               {a: {Weight: 50, Date: '01/01/2009'}}, 
               {a: {Weight: 50, Date: '01/01/2009'}}
];

// Here we define our new array that's going to contain our 'mutated' data

let newArr = [];

// Here we're going over our original array and push redefined data to our 'newArr'

array.map(x => {
  newArr.push(x.a);
});

// Now, let's see how that looks like :)

console.log(newArr);