【问题标题】:Make two arrays into json data将两个数组变成json数据
【发布时间】:2020-01-16 20:32:31
【问题描述】:

假设我有

A = [cat,dog,horse]
B = [angry,happy,sad]

call = {}

如何制作像这样的 json 对象

console.log(call.animal[2]) // horse

console.log(call.mood[2]) // sad

【问题讨论】:

标签: javascript json reactjs


【解决方案1】:

我假设你的数组是字符串。

const a = ['cat','dog','horse'];
const b = ['angry','happy','sad'];

call = {
  animal : a,
  fruit : b
}

console.log(call.animal[1]);

【讨论】:

    【解决方案2】:

    就这么简单。这是 es6 的一个新特性,动物和情绪变量成为对象中的 key-value(变量名及其值)。

    const animals = ['cat','dog','horse'];
    const emotions = ['angry','happy','sad'];
    
    const call = {animals, emotions};
    
    console.log(call.animals[2], call.emotions[2]);

    【讨论】:

      【解决方案3】:

      a 作为callanimal 属性,将b 作为callmood 属性:

      call = { animal: A, mood: B };
      

      如果数组是字符串,那么请确保在每个字符串周围加上',例如

      A = ['cat', ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-16
        • 1970-01-01
        • 2021-10-29
        • 2014-04-23
        • 2016-11-12
        • 1970-01-01
        相关资源
        最近更新 更多