How to get the index of an object in an array?

Hey!
How to get the index of an object in an array by the value of a property of that object?
This is the unique value of the property (for example, “uuid”).

Hi Roket,

You could run custom JavaScript code through the Function node which could extract the index of a certain object for you.

Using findIndex, this code would do the trick:

return [{
  json: {
    index: items.findIndex(item => item.json.uuid === "fd2c1a59-5a66-48c9-a370-1f5ea689f748")
  }
}]

Hope this helps :slight_smile:

3 Likes

@MutedJam, thanks for the answer! This code example does not work for me.
If you look up “uuid” from a specific object, then yes, this example code works, but I need to get the ordinal number for each element of the array.
Perhaps I am doing something wrong.

Ah, so you just want to have an additional key/value pair with the respective index for each of your objects? A straightforward way would be to just iterate over your array and add the respective index value.

With the n8n data structure in mind, a possible approach would be a simple for loop:

for (var i = 0; i < items.length; i++) {
  items[i].json.index = i;
}

return items;

2 Likes

Yes, this is what I wanted to get (a new key-value pair), perhaps I did not correctly describe the task.

1 Like

I will allow myself one more question on the same topic.
There is a set of properties for an object, how to get the ordinal number of each property, as well as a key-value pair (key = property name, value = ordinal number of this property). And so for each object in the array.
And return an array of objects, which contains all the same properties + a separate array property, for example, “property_order”.

Hi @Roket,

I’m not sure I fully understand the problem, so please correct me if I’m wrong. So say you have an item like the one shown in your screenshot:

{
  "uuid": "foo",
  "status": "bar",
  "col_1": "baz",
  "col_2": "qux",
  "col_3": "quux"
}

And you would like the item to have a new key property_order with an array value listing all other keys like so:

{
    "uuid": "foo",
    "status": "bar",
    "col_1": "baz",
    "col_2": "qux",
    "col_3": "quux",
    "property_order": [{
            "uuid": 0
        }, {
            "status": 1
        }, {
            "col_1": 2
        },
        {
            "col_2": 3
        },
        {
            "col_3": 4
        }
    ]
}

It would be best practice to build your logic agnostic to the order of keys in your JSON object. That’s because by definition this is an unordered set:

An object is an unordered set of name/value pairs

So maybe there’s an alternative approach that would achieve your goal?

If you still want to add the aforementioned property_order array to your items, it’s however rather simple to do so. This time, since you want to modify individual items, you’d use the Function Item node. You could then iterate through all available keys using Object.keys(), for example like so:

// Write keys in their own array
const keys = Object.keys(item);

// Add a new property_order array to our item
item.property_order = [];

// Now add an object for each key to property_order
for (var i = 0; i < keys.length; i++) {
    item.property_order.push({
        [keys[i]]: i // This uses a computed property name, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#new_notations_in_ecmascript_2015
    });
}

return item;

1 Like

Yes, almost everything is true. Only I need an array (“property_order”) of type:

[
{
"key": "uuid",
"order": 0 
},
{
"key": "status",
"order": 1
},
{
"key": "col_1",
"order": 2 
}...
]

I did not take into account this fact. Most likely, in my specific task, this will not be a problem, but for other tasks it is a logic vulnerability.
The point is that I’m trying to solve a small link of a big logical problem with the help of advice from the community. I noticed (historically) that if I try to describe a large problem, I don’t get an exact answer here (in the community), and if I break it down into subtasks and only send here those that I couldn’t solve on my own, then this is the most effective method.
Perhaps you need to describe a general large problem with examples of specific data in order to get a more complex and correct solution to it?

That part should be relatively easy to achieve, just change the structure of the object that’s being pushed to the property_order array. So replace

item.property_order.push({
    [keys[i]]: i
});

with your desired structure:

item.property_order.push({
    key: keys[i],
    order: i
});

The above should give you the desired output.

Fair point, I just wanted to make sure you don’t run into any trouble down the line :slight_smile:

2 Likes

@MutedJam, thanks for diving into my problem. Today I started reading this book https://eloquentjavascript.net/.
After 40 pages, it became clear what you did in the script for my task).

2 Likes