有没有办法从这些对象中提取数据值

时间:2020-01-13 20:17:23

标签: javascript json reactjs react-functional-component

我在图像中具有如下所示的数据,并且我正尝试从图像下方的json中提取Data数组。

enter image description here

数据具有诸如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数组。

非常感谢

3 个答案:

答案 0 :(得分:3)

这是一个简单的代码段,可返回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))

答案 1 :(得分: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));

或者也有点骇人听闻,对数组使用两次对象销毁,对数组进行索引:

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));

答案 2 :(得分:0)

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

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