【问题标题】:is there any way to extract the data values from these objects有没有办法从这些对象中提取数据值
【发布时间】:2020-04-30 13:50:45
【问题描述】:

我在图像中有如下数据,我正在尝试从下图中的 json 中提取 Data 数组。

数据具有 condition_type 等键值以及其他值。

我可以使用以下代码获取每个单独的值

const  submitcode = (data) => {
  const tasks = Object.values(data);
  console.log(tasks[0].Data[0]);
 }
 console.log(tasks[0].Data[0]);

请任何人建议是否有任何方法可以使用 react JS 从这 6 个对象中获取 Data 数组。

在此先感谢

【问题讨论】:

    标签: javascript json reactjs react-functional-component


    【解决方案1】:

    这是一个简单的 sn-p,它返回 Data 的数组

    const array = [
      {Cols: [], Data: [{condition_type: "1"}], title: "Environmental Condition"},
      {Cols: [], Data: [{condition_type: "2"}], title: "Ventilation"},
      {Cols: [], Data: [{condition_type: "3"}], title: "Thermal Comfort"},
      {Cols: [], Data: [{condition_type: "4"}], title: "Internal Loads"},
      {Cols: [], Data: [{condition_type: "5"}], title: "Exhaust"},
      {Cols: [], Data: [{condition_type: "6"}], title: "Misc"},
    ]
    
    console.log(array.map(({Data: [val]})=>val))

    或者如果您想直接访问特定键的值

    const array = [
      {Cols: [], Data: [{condition_type: "1"}], title: "Environmental Condition"},
      {Cols: [], Data: [{condition_type: "2"}], title: "Ventilation"},
      {Cols: [], Data: [{condition_type: "3"}], title: "Thermal Comfort"},
      {Cols: [], Data: [{condition_type: "4"}], title: "Internal Loads"},
      {Cols: [], Data: [{condition_type: "5"}], title: "Exhaust"},
      {Cols: [], Data: [{condition_type: "6"}], title: "Misc"},
    ]
    
    console.log(array.map(({Data: [{condition_type}]})=>condition_type))

    【讨论】:

    • 感谢您的建议,我需要为一些输入变量赋值,我可以继续像这样添加val.condition_type
    【解决方案2】:

    考虑到屏幕截图中的数组名为tasks,您可以使用具有对象和数组解构的映射:

    tasks.map(({ Data: [el] }) => el);

    const tasks = [{ Data: [{ a: 1, b: 2 }] }, { Data: [{ a: 3, b: 4 }] }];
    console.log(tasks.map(({ Data: [el] }) => el));

    或者也有点hacky,使用数组索引两次使用对象解构:

    tasks.map(({ Data: { 0: el } }) => el);

    const tasks = [{ Data: [{ a: 1, b: 2 }] }, { Data: [{ a: 3, b: 4 }] }];
    console.log(tasks.map(({ Data: { 0: el } }) => el));

    【讨论】:

    • 非常感谢您的支持,我可以继续访问像这样的值吗el.a
    • 当然可以,你也可以直接在参数中解构它们
    【解决方案3】:

    您可以映射父级(任务数组)并获取子级(数据数组)

    const result = tasks.map(s => s.Data[0]);
    //result contains array of Data objects
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      相关资源
      最近更新 更多