【问题标题】:Javascript Map (Object) doesn't format correctlyJavascript 地图(对象)格式不正确
【发布时间】:2018-02-02 18:14:50
【问题描述】:

我有一个地图数组,每个在控制台中看起来像这样:

Map[10]
{"chartType" => "horizontalBar"}
{"data" => 
List[4]
}
{"description" => "Everything black"}
{"detailUrl" => ""}
{"featuredStepIndex" => 1}
{"id" => 542}
{"isValid" => false}
{"stepIndex" => 1}
{"type" => "results"}

我有一个 React 组件,它接受这个 Maps 数组并呈现输出。我正在尝试获取另一个数据源并像上面一样对其进行格式化以传递给 React 组件。

当我使用以下代码创建新地图数组时:



resultsSteps.forEach((item) => {
    const newMapStep = new Map();    
    newMapStep.chartType = 'horizontalBar';
    const itemDescription = item.get('description');
    newMapStep.description = itemDescription;
    newMapStep.featured = 'false';
    newMapStep.detailUrl = '';
    newMapStep.featuredStepIndex = 1;
    const itemId = item.get('id');
    newMapStep.id = itemId;
    newMapStep.isValid = 'false';
    newMapStep.type = 'results';
    const itemOptions = item.get('options');
    newMapStep.data = itemOptions;
    const itemAnswers = item.get('userAnswers');
    newMapStep.userAnswers = itemAnswers;

    newResultsSteps.push(newMapStep);
  });

我得到一个在控制台中看起来不同的 Map 对象:

Map
chartType
:
"horizontalBar"
data
:
List[4]
description
:
"Everything black"
detailUrl
:
""
featured
:
"false"
featuredStepIndex
:
1
id
:
542
isValid
:
"false"
type
:
"results"
userAnswers
:
List[2]
_c
:
Map(0) {}
size
:
(...)
__proto__
:
Map

...它看起来不像它正在替换的那个,每个条目都有 {'' => '' }。如何创建与该语法匹配的新地图?

【问题讨论】:

  • 1) 你为什么关心它在 console 中的样子?和 2) 这不是您添加地图条目的方式,请使用 set
  • 因为 React 组件需要特定格式的数据,而新创建的 Map 的格式与之前的格式不匹配,因此无法在组件中正确呈现。
  • 您只是将对象属性附加到Map 对象。使用.setmethod
  • 对每个集合使用 .set 方法而不是点注释会产生相同的结果。 linter 更喜欢点注释,所以这就是我使用的。
  • 控制台可以显示任何它想显示的内容,ECMAScript 规范中没有任何内容说 Map 必须显示 ({key => value})。您必须查看该特定 React 组件的文档。

标签: javascript object foreach javascript-objects


【解决方案1】:

你必须使用 .set 方法

resultsSteps.forEach((item) => {
    const newMapStep = new Map();    
    newMapStep.set('chartType', 'horizontalBar');    
});

【讨论】:

    猜你喜欢
    • 2020-11-05
    • 2011-08-26
    • 2015-05-28
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    相关资源
    最近更新 更多