question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to correctly organize array of objects form?

See original GitHub issue

Bug, Feature, or Question?

Question

At the moment there is only one example of FieldArray which handles array of strings. https://github.com/jaredpalmer/formik#fieldarray

Is it possible to implement an array of objects? In case each of friends has firstName, lastName and age for example.

What is a proper way to do it?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:14 (6 by maintainers)

github_iconTop GitHub Comments

52reactions
latviancodercommented, Mar 13, 2018

Here is what I used in my app:

<Form>
    <FieldArray
        name="friends"
        render={arrayHelpers => (
            <div>
                {values.friends.map((friend, index) => (
                    <div key={index}>
                        <Field name={`friends.${index}.name`}/>
                        <Field name={`friends.${index}.age`}/>
                        <button
                            type="button"
                            onClick={() => arrayHelpers.remove(index)}
                        >
                            -
                        </button>
                    </div>
                ))}
                <button
                    type="button"
                    onClick={() => arrayHelpers.push({ name: '', age: '' })}
                >
                    +
                </button>
            </div>
        )}
    />
</Form>

And here is an example validationSchema:

const friendValidationSchema = object().shape({
    name: string().required('name required'),
    age: number().required('age required').typeError('age must be a number')
});

const validationSchema = object().shape({
    friends: array().of(friendValidationSchema)
});
8reactions
Nemsaecommented, Feb 19, 2019

@latviancoder @jaredpalmer Is it possible to combine the creation of a new element with an existing<FieldArray />?

In the same example @latviancoder posted, the button to add a new element into the array has this handler onClick={() => arrayHelpers.push({ name: '', age: '' })} from below:

<Form>
    <FieldArray
        name="friends"
        render={arrayHelpers => (
            <div>
                {values.friends.map((friend, index) => (
                    <div key={index}>
                        <Field name={`friends.${index}.name`}/>
                        <Field name={`friends.${index}.age`}/>
                        <button
                            type="button"
                            onClick={() => arrayHelpers.remove(index)}
                        >
                            -
                        </button>
                    </div>
                ))}
                <button
                    type="button"
                    onClick={() => arrayHelpers.push({ name: '', age: '' })}
                >
                    +
                </button>
            </div>
        )}
    />
</Form>

In this example this would just push { name: '', age: '' } element into the array of friends.

However, what if my form is a bit more complex, in that I want to render fields for the new element that I want to push into the array of this.props.values.friends.

The code that I imagine/hope for would be something like this (which I realize doesn’t make much sense):

<Field name={`friends.${indexToBeAdded}.name`}/>
<Field name={`friends.${indexToBeAdded}.age`}/>

Currently what I have to do is create a separate set of fields for the new element…

<Field name={`new_friend_name`}/>
<Field name={`new_friend_age`}/>

Which means I have to have separate validation for those new fields new_friend_name and new_friend_age, and add a special handler that will add the new element into the existing this.props.values.friends using this.props.setValues upon successful validation.

Is there a more elegant way to accomplish this, where I can put the creation of a new element under the umbrella of the <FieldArray />?

Hopefully I’m illustrating the problem clearly enough. Chose not to create another issue as it seems closely tied to this, but certainly don’t mind creating another one if you guys think so.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Quick Tip: How to Sort an Array of Objects in JavaScript
To sort an array of objects, use the sort() method with a compare function. A compareFunction applies rules to sort arrays by defined...
Read more >
Sort an Array of Objects in JavaScript
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
Read more >
Sort array of objects by string property value - Stack Overflow
The sort method can be modified to sort anything like an array of numbers, strings and even objects using a compare function. A...
Read more >
Array.prototype.sort() - JavaScript - MDN Web Docs
The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default...
Read more >
JavaScript Problem: Sorting an Array of Objects - YouTube
The sort method of JavaScript arrays allows the use of a callback function. For many sort features, this is necessary.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found