WildThing
WildThing

Reputation: 1285

ant design custom Form List: How to handle Array inside an array

The data I receive from the backend looks something like this:

 const pronounsExample = [
  [
    {
      id: '62f51edbbd529a9306052013',
      title: 'He / Him / His',
    },
  ],
  [
    {
      id: '62f51ef8bd529a9306052014',
      title: 'She / Her / Her',
    },
  ],
]

I use Form.List whenever I have an array of objects but the above value is different, because it is array inside an array and then an object inside, I would like to build a form Item so that users can manipulate these values and the Form should return the requred data in the above format:

Here is what I use when I have an Array of Objects:

 <Form.List name="pronouns" initialValue={data?.pronouns}>
        {(fields, { add, remove }) => {
          console.log('List Fields', fields)
          return (
            <div>
              <Row gutter={[16, 16]} justify="end">
                <Col>
                  <Button onClick={() => add()} className="mb-2">
                    <PlusOutlined /> {messages.buttons.add}
                  </Button>
                </Col>
              </Row>
              {fields.map((field) => (
                <Row key={field.key} gutter={[16, 16]}>
                  <Form.Item name={[field.name, 'id']} hidden>
                    <Input />
                  </Form.Item>
                  <Col flex={1}>
                    <Form.Item name={[field.name, 'nameTranslate']}>
                      <Input />
                    </Form.Item>
                  </Col>
                  <Col>
                    <Button
                      type="danger"
                      onClick={() => remove(field.name)}
                      disabled={fields.length === 0}
                      icon={<DeleteOutlined />}
                    />
                  </Col>
                </Row>
              ))}
            </div>
          )
        }}
      </Form.List>

helpful links:

https://ant.design/components/form#formlist

Upvotes: 0

Views: 3619

Answers (1)

Banus
Banus

Reputation: 94

Let's say, I guess your problem is converting an array of arrays of objects to an array of object, right?

If yes, my solution is:

let filteredArray = [];
for (let i = 0; i < pronounsExample.length; i++){
       filterdArray.push([...pronounsExample[i]])
    }

So, initialValues = filteredArray[0]

Upvotes: 1

Related Questions