繁体   English   中英

将数组转换为具有键/值对的对象

[英]Converting an array into an object with key/value pairs

我还在学习JavaScript,所以如果这似乎是一个补救问题我会提前道歉。

我以数组的形式从API调用接收数据,如下所示:

arr = ['topic1',497,'topic2',591,'topic3',17,'topic4',980]

虽然从该数组中看不出来,但每个主题字符串后面的数字是前一主题的计数。

我想在React应用程序中处理这些数据,即将其映射到表或其他数据结构。 但是当这些值是匿名的时候,这非常困难。

所以,我想采用这个数组并将其转换为具有键/值对的对象。 所以,在工作某种循环/过滤器/地图/等之后。 在阵列上,我需要最终得到这个:

newArr = [
  {topic: 'topic1', count: 497},
  {topic: 'topic2', count: 591},
  {topic: 'topic3', count: 17},
  {topic: 'topic4', count: 980},
]

我已经尝试了很多技巧,包括使用词典,地图,地图,过滤器,forEach,for ... in,以及比我在这一点上记忆更多的技巧。 是的,我搜索了许多网页和论坛。 问题是,我的问题包括一些JavaScript的构建块,所以我找到的答案从来都不足以解决我的问题。

我成功地过滤掉了数组中的偶数和奇数元素,如下所示:

let x = arr.filter((element, index) => {
  return index % 2 === 0; filter elements located at an even index
});

let y = arr.filter((element, index) => {
  return index % 2 === 1; filter elements located at an odd index
});

但我从来没有成功地得到我需要的结果。 有人可以帮我指点正确的方向吗?

我正在使用React,所以请随意提出现代JS技术。 谢谢!

您需要遍历API响应并从数组中构建对象。

let objectArray = []

for(let i = 0; i < arr.length - 1; i+=2){
    objectArray.push({"topic": arr[i], "count": arr[i+1]})
}

我确信有一种更简单的方法可以做到这一点,但这将为您提供所需。

在jsFiddle上看到它的行动: https ://jsfiddle.net/L6023fn6/1/

您可以使用array.reduce来获取数组并发出聚合值,数组,对象或其他内容。 完整的实施将是:

const newArr = arr.reduce((fonts, value, index) => {
   if (0 === index % 2) {
     fonts.push({ topic: value });
   } else {
     // output array will be half the size of the input hence the / 2
     fonts[Math.ceil(index / 2 - 1)].count = value;
   }

   return fonts;
}, []);

如果您愿意使用像lodash这样的外部库, lodash您可以更轻松地使用它,因为它会为您提供数组块。

const newArr = _.zipWith(_.chunk(arr, 2), a => ({ topic: a[0], count: a[1] }));

从你的问题来看, arr是一个字符串,数字......模式,我认为你可以做到这一点。

const arr = ['topic1',497,'topic2',591,'topic3',17,'topic4',980];
const result = [];

for(let i=0; i<arr.length; i+=1) {
 typeof arr[i] === 'string' 
 ?
  result.push({topic: arr[i], count: arr[i+1]})
:
null;

}

暂无
暂无

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

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