迭代字典React Js无法正常工作

问题描述 投票:0回答:2

我的代码中有一个名为CarValues的字典,其中包含以下数据:

词典:CarValues

key ==> string

值==>数组

  1. key => Honda,Value =>白色,黄色,红色,橙色
  2. key =>丰田,价值=>白色,黄色,绿色,黑色
  3. Key => Volkswagen Value => 123,456,343

我想迭代键并生成如下所示的字符串:

var merge = HondaCar ='white'&HondaCar ='yellow'&HondaCar ='red'&HondaCar ='orange'&ToyotaCar ='white'&ToyotaCar ='yellow'&ToyotaCar ='green'&ToyotaCar ='black'&VolkswagenCar = 123&VolkswagenCar = 456&VolkswagenCar = 343

我在类中的一个方法中有类似下面的内容:

    var merge = '';
    Object.getOwnPropertyNames(this.state.CarValues).map(function(key){
        for (var x in key.values) {
            merge= merge.concat('&' + key + '='" + x + "'");
        }

我不确定有什么问题,但上述情况并不奏效。它表示在执行时键未定义。

也试过下面,

    Object.keys(this.state.CarValues).map((key) => (
        **for (var value in  vals[key] }) {**
            merge = merge.concat('&' + key + '='" + x + "'");
        }
    **))**

但是上面的汇编在编译时抛出了错误,表达式在粗体突出显示的行中。

javascript reactjs react-native
2个回答
2
投票

你可能会尝试这样的事情:(别忘了添加this.state.

const CarValues = {
    Honda: ['white', 'yellow', 'red', 'orange'],
    Toyota: ['white', 'yellow', 'green', 'black'],
    Volkswagen: [123, 456, 343]
}

var q = Object.entries(CarValues)
    .map( ([key, value]) => `${key}=` + value.join(`&${key}=`))
    .join('&');

console.log(q)

0
投票

假设您的数据结构如下:

const cars = {
  Honda: ["white", "yellow", "red", "orange"],
  Toyota: ["white", "green"],
  Volkswagon: [123, 456]
};

而且你想要输出:HondaCar ='white'&HondaCar ='yellow'&HondaCar ='red'&HondaCar ='orange ToyotaCar ='white'CanzenCar ='green'VolkswagonCar = '123'VolkswagonCar ='456'

这个怎么样:

const { cars } = this.state;
const keys = Object.keys(cars);
const s = keys.reduce((acc, car) => {
  const colours = cars[car].map(val => {
    return `${car}Car='${val}'`;
  });
  return `${acc}${colours.join('&')}`;
}, "");
console.log(s);
© www.soinside.com 2019 - 2024. All rights reserved.