-1

Here, i have included a my example code. I want to insert (push) data to my multidimensional json.

  const answers = [
    { id: "1", text: "192.168.1.1" },
    { id: "2", text: "127.0.0.1", correct: true },
    { id: "3", text: "209.85.231.104" },
    { id: "4", text: "66.220.149.25" },
  ];

And i want to insert element like { id: "5", text: "66.220.149.20" }, to the last position. and the final result should looks like

  const answers = [
    { id: "1", text: "192.168.1.1" },
    { id: "2", text: "127.0.0.1", correct: true },
    { id: "3", text: "209.85.231.104" },
    { id: "4", text: "66.220.149.25" },
    { id: "5", text: "66.220.149.20" }
  ];

How to achieve this one with multidimensional json data with react-native? Or is it possible to do that?

Nikola Marinov
  • 223
  • 1
  • 11
  • There is no JSON here. JSON is a text format. See [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/q/2904131/215552). Also, you've shown data, but not your attempt to solve the problem yourself. A hint: the array shown here is unidimensional. It is an array of objects. – Heretic Monkey Jun 28 '21 at 20:06
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push – Matt Jun 28 '21 at 20:08

1 Answers1

0
  1. I don't understand how this is multi-dimensional. Typically the word multi-dimensional pertains to Arrays and look something like this.

    [[1, 2, 3], [4, 5, 6]]

  2. I think what you are looking for is a way to find the highest id value in the JSON and add a new object that is (the highest id value + 1).

Your code should look something like this.


let highestVal = answers.reduce(
    (highest, {id}) => highest > parseInt(id) ? highest : parseInt(id),
    0
)

answers.push({id: highestVal, text: '...', ...})

Miguel Coder
  • 1,896
  • 19
  • 36