2

need some help I have an array like that

usernames=[
  username1{name : 'mark' , number : '10' , color:'green'},
  username2{name : 'jeff' , number : '15' , color:'blue'} ,
  username3{name : 'joy' , number : '30' , color:'yellow'}]

how to delete the whole line by object name (username1/username2)?

3 Answers3

1

Assuming you have an object, then with

var usernames = {
        username1: { name: 'mark', number: '10', color: 'green' },
        username2: { name: 'jeff', number: '15', color: 'blue' },
        username3: { name: 'joy', number: '30', color: 'yellow' }
    };

delete usernames.username2;
console.log(usernames);    

Otherwise, if you have an array with objects, then with

var usernames = [
        { username1: { name: 'mark', number: '10', color: 'green' }},
        { username2: { name: 'jeff', number: '15', color: 'blue' }},
        { username3: { name: 'joy', number: '30', color: 'yellow' }}
    ];

usernames.splice(1, 1);
console.log(usernames);    
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
0

You need this:

usernames.splice(1,1);

Removes the second element only.

The first parameter is the index of the item to remove, the second is the number of elements to remove.

How do I remove a particular element from an array in JavaScript?

EDIT

var index = usernames.indexOf(username2);
usernames.splice(index,1);
Community
  • 1
  • 1
0

Use the splice method

var usernames= [
  {"username1": {name : 'mark' , number : '10' , color:'green'}},
  {"username2": {name : 'jeff' , number : '15' , color:'blue'}} ,
  {"username3": {name : 'joy' , number : '30' , color:'yellow'}}]

usernames.splice(1,1);
console.log(usernames);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Richard Hamilton
  • 22,314
  • 9
  • 45
  • 77