1

I have a 2d array called MyUsernames.

If I write console.log(MyUsernames) I see this:

0: {id: "5", name: "quirky.subdued"}
1: {id: "6", name: "phyllida.skeg"}
2: {id: "7", name: "duff.anarchist"}
3: {id: "9", name: "relashio.articulate"}

I am trying to access the name part of an element in the array.

I output the records in MyUsernames via this loop:

var hst = document.getElementById("usernames");

for (var i = 0; i < MyUsernames.length; i++) {  
    var un1 = MyUsernames[i].name;
    hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>" + un1 + "</a></li>";
}

This is the deleteById bit of code:

var deleteById = function ( self ){

    this_id = self.id;
    this_word = MyUsernames[this_id].name;

}

My problem is that I am sending e.g. an ID value of 9 to extract the Name relashio.articulate.

However, I am trying to access that by this bit of code:

this_word = MyUsernames[this_id].name;

That doesn't work, because as per the console output, the bit I want in my example would be access via:

MyUsernames[3].name;

And not:

MyUsernames[9].name;

The problem is I can't send an ID value of 3 because I only have the ID value of the record from MyUsernames which is 9.

Is there a way I can access the "name" part of the array, by its corresponding ID?

1
  • You probably want to convert array to object and be able to use users['9'].name; I hope you find posted answer useful, Good luck! [stackoverflow.com/a/64400342/14435535] Commented Oct 17, 2020 at 23:05

5 Answers 5

2

I think you are looking for Array.prototype.find. You can provide a set of criteria inside a function and find will give one result back if your criteria matches.

You use it like this

var usernames = [];
usernames.push({id: "5", name: "quirky.subdued"});
usernames.push({id: "6", name: "phyllida.skeg"});
usernames.push({id: "7", name: "duff.anarchist"});
usernames.push({id: "9", name: "relashio.articulate"});

function findUsername(id) {
    var username = usernames.find(function(username) { return username.id === id });
    return username;
}

var user5 = findUsername("5");
document.write('Find result 1: ' + user5.name);

document.write('<br />');

var user9 = findUsername("9");
document.write('Find result 2: ' + user9.name);

Here my JsFiddle: https://jsfiddle.net/rtL87veq/11/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Patrick for your helpful reply. On your JsFiddle - you are passing 5 and 9 to your function, but both return the same quirky.subdued value?
@4532066 Thanks for seeing my error. I corrected the example
1

Convert Array to Object

By implement User Id as primary key for new object variable you'll be able to find user via users[9].name

Output:

relashio.articulate
   

Define new object variable and do for loop ensure you marking user id as the primary key. Then, save rest of object data in same key. e.g.

var users = {};

        // for loop all your users in 'array'
        for (var i = 0; i < MyUsernames.length; i++) {

        // hold found user in variable
            var user = MyUsernames[i];

        // mark user id as the primary key then save rest of object data in same key
            users[user.id] = user;
        };

Source Code

var MyUsernames = [{
  id: "5",
  name: "quirky.subdued"
}, {
  id: "6",
  name: "phyllida.skeg"
}, {
  id: "7",
  name: "duff.anarchist"
}, {
  id: "9",
  name: "relashio.articulate"
}];
    
    // define object variable
        var users = {};
        // for loop all your users in 'array'
        for (var i = 0; i < MyUsernames.length; i++) {
        // hold found user in variable
            var user = MyUsernames[i];
        // mark user id as the key then save rest of object data in same key
            users[user.id] = user;
        };
        
        // Print the value of key 'name' for user id '9'
        console.log(users[9].name)

2 Comments

Hi @i3z - that's really helpful. I would have marked this as the correct answer, but the other route also worked from Patrick. Your method is very smart - thank you :-)
Thank you! I am glad that helped you, happy coding =) @4532066
0

Array.find O(n) is an option and search the array by inner props.

const usernames = [{
  id: "5",
  name: "quirky.subdued"
}, {
  id: "6",
  name: "phyllida.skeg"
}, {
  id: "7",
  name: "duff.anarchist"
}, {
  id: "9",
  name: "relashio.articulate"
}]


const target = usernames.find(({ id }) => id === "9")

console.log(target)

It is not supported in Internet Explorer. Consider using Array.filter if your target browser is IE9+

const usernames = [{
  id: "5",
  name: "quirky.subdued"
}, {
  id: "6",
  name: "phyllida.skeg"
}, {
  id: "7",
  name: "duff.anarchist"
}, {
  id: "9",
  name: "relashio.articulate"
}]


const [target] = usernames.filter(({ id }) => id === "9")
// Filter returns an array of matches. Destructing helps to get the first match 

console.log(target)

Comments

0

Change this line:

hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>" + un1 + "</a></li>";

to this:

hst.innerHTML += "<li>" + "<a id='" + i + "' href='#content' onclick='deleteById(this)'>" + un1 + "</a></li>";

Now, self.id will return 3.

Comments

0

I'd consider whether a js Map object is a more suitable structure, which may turn on whether the ordering of the collection -- and therefore the array index -- is relevant or just a side effect of your grouping. Any value (both objects and primitive values) may be used as either a key or a value.

You can generate, access and manipulate a Map as follows with objs' id as the key, and obj itself as value in each Map pair.

    let dataMap = new Map();
    
    // Set key to id and obj to value for each Map pair
    MyUsernames.forEach(obj => dataMap.set(obj.id, obj));
    
    // Access value (obj) with key (id) of 2
    const objIdTwo = dataMap.get(2)

    // Determine whether pair with key (id) of 3 exists in Map
    const objIdThree = dataMap.has(3)

    // Remove pair with key (id) of 4 from Map
    dataMap.delete(4)
    
    // A Map object iterates its elements in insertion order — a for...of loop 
    // returns an array of [key, value] for each iteration.
    for (let [id, obj] of dataMap) {
       console.log(id + ' = ' + obj)
    }

   // If needed, Map can be converted to 2d-array
   const arr2d = Array.from(dataMap)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.