Mayuresh Patil
Mayuresh Patil

Reputation: 2200

How to push JSON data in two dimensional array?

I am trying to get a structure like

var tableData= [
  ['Hfbj'],
  ['Hygh'],
  [6],
  ['mayur'],
  [2563458952]
]

Here is my JSON data:

data:{
  "address"': "Hfbj"
  "id": 6
  "landmark": "Hygh"
  "name": "mayur"
  "phone": 2563458952
  "title": "aaa"
}

I am using react-native-table-component in which that type of structure needed. For that, I am doing the following but it showing data.map is not function and undefined.

let newdata = this.state.tableData[0].push(
  [responseJson.data.title],
  [responseJson.data.title]
);

this.setState({
  tableData: newdata
});

How can I achieve it?

Upvotes: 0

Views: 1466

Answers (2)

Jeto
Jeto

Reputation: 14927

You could make use of Object.values and Array.map:

var reponseJson = {
  data: {
    "address": "Hfbj",
    "id": 6,
    "landmark": "Hygh",
    "name": "mayur",
    "phone": 2563458952,
    "title": "aaa"
  }
};

var newData = Object.values(reponseJson.data)
  .map(item => [item]);

console.log(newData);

Note that I used the responseJson name to match your question, but as @Andreas pointed out, this is an object, not JSON.

If you need only certain columns (as requested in the comments below), use Object.keys and Array.filter on them before rebuilding the array:

var reponseJson = {
  data: {
    "address": "Hfbj",
    "id": 6,
    "landmark": "Hygh",
    "name": "mayur",
    "phone": 2563458952,
    "title": "aaa"
  }
};

var keysToKeep = ['address', 'landmark', 'title'];

var newData = Object.keys(reponseJson.data)
  .filter(key => keysToKeep.includes(key))
  .map(key => [reponseJson.data[key]]);

console.log(newData);

Upvotes: 1

dan
dan

Reputation: 1364

.map Is for arrays, whereas your responseJson.data is an Object. To get turn that Object into an array of its values you can do Object.values(responseJson.data)

Upvotes: 1

Related Questions