Katyellen
Katyellen

Reputation: 313

How to handle multiple arrays?

I have an array that inside it has several other arrays.

What I need is to find the array that has an object with name: "tax-payer-identification". Change the variable's value required: true to false.

But the problem is that it's an array of arrays and I don't know how to manipulate it, change the variable value, and return the array to be used.

Can you tell me how can I do this? Thank you very much for any help.

enter image description here

import React from "react";
import { data } from "./data";
import "./styles.css";

const App = () => {
  const getData = () => {
    data.map((item) => item.map((item2) => console.log(item2)));
  };

  console.log(getData());

  return <div>App</div>;
};

export default App;

export const data = [
  [{
    // some data
  }],
  [{
      // some data
    },
    {
      // some data
    }
  ],
  [{
    // some data
  }],
  [{
    name: "tax-payer-identification",
    type: "text",
    regex: "^.{0,20}$",
    inputName: "vatNumber",
    required: true,
    maxLength: 20,
    minLength: 0
  }],
  [{
    // some data
  }],
  [{
    // some data
  }],
  [{
      // some data
    },
    {
      // some data
    }
  ],
  [{
      // some data
    },
    {
      // some data
    }
  ]
];

Upvotes: 0

Views: 89

Answers (2)

Jay F.
Jay F.

Reputation: 314

This recursive function would do the same and can be used when the array structure is not predictable:

const updateArray = (dataArray, updates = {}) => {
    let result = [];

    const updateApply = (objData) => {
        if (updates && Object.keys(updates).length > 0) {
            Object.keys(updates).map((key) => {
                if (objData.hasOwnProperty(key)) {
                    objData[key] = updates[key];
                }
            });
        }

        return objData;
    };

    for (const index in dataArray) {
        if (Array.isArray(dataArray[index])) {
            result[index] = dataArray[index].map((e) => {
                return Array.isArray(e)
                    ? updateArray([...e], updates)
                    : updateApply(e);
            });
        } else {
            result[index] = updateApply(dataArray[index]);
        }
    }

    return result;
};

Calling the function with the object(s) that need to be changed:

updateArray(data, { require: false });

Upvotes: 0

JSEvgeny
JSEvgeny

Reputation: 2750

Something like that could possibly work:

const output = data.map(item => item.map(nested => {
    if (nested.name === "tax-payer-identification") {
        nested.required = true
    }
    return nested
}))

Upvotes: 2

Related Questions