如何索引相似的对象值并将其显示在它们旁边?Javascript/Rect/ES6



我当前正在接收对象segregatedData作为道具。这个对象包含几个属性,但我们将关注的是segregatedData.type1。基本上,这只是一个字符串数组,比如['water','fire','water',earth']。我希望能够打印出每个字符串,然后在它旁边显示这个值重复了多少个实例。因此,在本例中,预期输出为water-2, fire-1, earth-1。当然,我们必须删除重复项。

到目前为止,我拥有的是:

import React from "react";
import { Typography } from "@material-ui/core";
function TypesText(props) {
const { segregatedData } = props;
return (
<>
<Typography>Type1:</Typography>
{segregatedData.length && segregatedData.map((data) => data.type1 + " ")}
</>
);
}
export default TypesText;

相当基本的是,它只打印每个type1属性,并使用一个空白字符串作为分隔符。任何能为我指明正确方向的东西都将不胜感激。

使用segregatedData.type1.reduce输出数组,该数组通过映射并使用字符串来查找输出数组中的出现项。search查找出现项,然后在末尾递增整数。

看看下面的代码示例。测试

const arr = ['water','fire','water', 'earth'];
let val = arr.reduce((resultarr, item) => { 
const val = resultarr.find(item1 => item1.search(item) !== -1) 
const ind = resultarr.findIndex(item1 => item1.search(item) !== -1) 
if (val == undefined) {
resultarr.push(item + "-" + 1)
}
else {
const i = val.search("-")
const num = parseInt(val.substring(i+1))
const nval = item + "-" + (num+1)
resultarr[ind] = nval;
}
return resultarr
}, [])
alert(val);

最新更新