One Liners to Edit Object Arrays in JavaScript

If you have an array of objects, for example Posts from the WordPress REST API (or WP-API), how do you manipulate them?

Let’s say we make a GET request to an API endpoint, such as https://apppresser.com/wp-json/wp/v2/posts. We get back an object array, we can oversimplify it like this:

const posts = [
    {
        "id": 1,
        "title": {
            "rendered": "Post One"
        }
    },
    {
        "id": 2,
        "title": {
            "rendered": "Post Two"
        }
    },
    {
        "id": 3,
        "title": {
            "rendered": "Post Three"
        }
    }
]

If we want to find a certain post by a value, such as ID, we could use array.forEach() like this:

posts.forEach( (value, i) => {
  if( value.id === someId ) {
   // do something with posts[i]
  }
}

But it’s much more fun (and more efficient maybe?) to use one liners. Let’s check them out.

Find an Object in an Array of Objects by Value

Problem: the user searches for a post with a title of “Post Three.” I need to return the entire post and all I have is the title.

Solution: Find the object using array.find()

// One Liner
posts.find(p => p.title.rendered === searchTerm );

Full example:

let searchTerm = "Post Three";
const post = posts.find(p => p.title.rendered === searchTerm );
console.log(post);
// expected result of log
{
    "id": 3,
    "title": {
        "rendered": "Post Three"
    }
}

Once we have the post data, we could also edit the data and send it back to save.

Remove an Object in an Array of Objects by Value

Problem: user requests to delete an object by the item ID.

Solution: To remove an object from an object array, we need the index. We can use array.map() to turn our post object into an array of IDs, and then find the index of our ID.

Solution: Find the object using array.findIndex()

// One Liner
let removeIndex = posts.findIndex( post => post.id === 37 );

Full example:

// find the index of post with id of 37
let removeIndex = posts.findIndex( post => post.id === 37 );
// remove the entire post from our array
posts.splice(removeIndex, 1);

Edit an Object in an Object Array

Problem: user requests to edit an object by object ID.

Solution: get the object index then edit a value.

// One Liner
posts.find((o, i) => { if (o.id === postToEdit) { posts[i].title.rendered = "I Changed the Title"; } });

Full example:

const postToEdit = 2;
posts.find((o, i) => {
    if (o.id === postToEdit) {
        posts[i].title.rendered = "I Changed the Title";
        return true; // stop searching
    }
});
console.log( posts );
// expected log
const posts = [
    {
        "id": 1,
        "title": {
            "rendered": "Post One"
        }
    },
    {
        "id": 2,
        "title": {
            "rendered": "I Changed the Title"
        }
    },
    {
        "id": 3,
        "title": {
            "rendered": "Post Three"
        }
    }
]

Posted

in

by

Tags: