0

I have array of objets like:

var MyArray = [] ,
    Person = {}, 

[
    {
        name: 'John',
        surname: 'Smith',
        age: '22'
    },
    {
        name: 'Jesica',
        surname: 'Garou',
        age: '31'
    },
    {
        name: 'Max',
        surname: 'Jolie',
        age: '50'
    }
]

I want to check , if my data has name 'John' that don't add new person , if not , then add new person with name 'John' and etc.

Thanks in advance .

  • Please show what you have tried. Stackoverflow is not a free code writing service. The objective here is to help you fix **your code** – charlietfl Jul 29 '17 at 12:33
  • @charlietfl i create objets and pass it to array , but in this step i cand find any solution for this. –  Jul 29 '17 at 12:35

8 Answers8

3

You could deal with it using Array#find. I assume that you want to mutate your original array.

let arr = [{
    name: 'Jesica',
    surname: 'Garou',
    age: '31'
  },
  {
    name: 'Max',
    surname: 'Jolie',
    age: '50'
  }
];

const obj = {
  name: 'John',
  surname: 'Smith',
  age: '22'
};

const ensure = ({ name, ...z }) => {
  if (!arr.find(v => v.name === name)) {
    arr.push({ name, ...z });
  }
}

ensure(obj);

console.log(arr);
kind user
  • 40,029
  • 7
  • 67
  • 77
  • I meant _map_ abstractly, not in the sense of the function, but rather that what would have an `undefined` result had a `null` substituted for it for no gain. – Aluan Haddad Jul 29 '17 at 12:45
  • Definitely the best answer. It would be even better if `exist` was renamed to `ensure` and `==` was changed to `===` :) – Aluan Haddad Jul 29 '17 at 12:55
2

You can use map but you have to know that map iterates through all elements in the array, whereas findIndex returns the first element index that equals the condition and stops the loop.

var MyArray = [
    {
        name: 'John',
        surname: 'Smith',
        age: '22'
    },
    {
        name: 'Jesica',
        surname: 'Garou',
        age: '31'
    },
    {
        name: 'Max',
        surname: 'Jolie',
        age: '50'
    }
];

if(MyArray.findIndex(index => index.name === "John") > -1)
  console.log("Found!");
else
    console.log("Not found!");
Niroda
  • 320
  • 1
  • 3
  • 13
2

To check if a name already exists in an array, you can make use of array.some function. It will check if name provided already exits or not.

If not then you can write the code to push the object in the array.

I have used the sample names John and Anne. For John, the function isAlreadyPresent returns true. For Anne, it returns false.

let arr = [
    {
        name: 'John',
        surname: 'Smith',
        age: '22'
    },
    {
        name: 'Jesica',
        surname: 'Garou',
        age: '31'
    },
    {
        name: 'Max',
        surname: 'Jolie',
        age: '50'
    }
];

function isAlreadyPresent(name) {
  return arr.some(a => a.name === name );
}

console.log('John already exists?',isAlreadyPresent('John'));
console.log('Anne already exists?',isAlreadyPresent('Anne'));
Anurag Singh Bisht
  • 2,683
  • 4
  • 20
  • 26
0

You'll need to loop through all of the objects and check each of their name values. At worst runs in O(n) time.

For example, to check if "John" is a name in the array:

var inArray = false; // Have we found the name in the array yet?
for (var i = 0; i < MyArray.length; i++) { // Loop through the array of objects
    if (MyArray[i].name=="John") { // If the name field is equal to "John"
        inArray = true; // Name is in the array
        break; // Exit the loop
    }
}
xlm
  • 6,854
  • 14
  • 53
  • 55
Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55
  • Hi . There is no way without "for" ? its little bit slowly for my case. –  Jul 29 '17 at 12:36
  • 1
    @ArikDonowan well *something* has to iterate through the array; there's no magic. If you need faster access, you need a more sophisticated data structure. – Pointy Jul 29 '17 at 12:40
0

Maybe a name Map could be useful:

var byNam e =new Map(myArray.map(el=>[el.name,el]));

So you can easily do:

if (byName.has("John")){
  alert("already exists");
} else {
  var obj = { name: "John" };
  Map.set(obj.name,obj);
  myArray.push(obj);
}

The upper can be achieved with a Set also, but you may also want to do this:

byName.get("John").age=15;
xlm
  • 6,854
  • 14
  • 53
  • 55
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • I don't see the point of using `Map`. This does a lot of extra work and it introduces a parallel data structure that has to be kept up to date. The `byName` approach would be good if it was a function that always returned current the elements in the array by name. – Aluan Haddad Jul 29 '17 at 13:00
  • 1
    @aluan haddad just because youre not seing the usecase is not a reason to give a downvote. If youre not understanding sth, it would be enough to ask... – Jonas Wilms Jul 29 '17 at 13:07
  • That is true. I apologize for my rash behavior. – Aluan Haddad Jul 29 '17 at 13:08
0
var searchTerm = "John",
index = -1;
for(var i = 0, len = MyArray.length; i < len; i++) {
    if (MyArray[i].name === searchTerm) {
        alert("matched string");
        index = i;
        break;
    }
}
xlm
  • 6,854
  • 14
  • 53
  • 55
rkeshri
  • 103
  • 1
  • 8
  • 2
    While this code may answer the question, it would be better to explain how it solves the problem without introducing others and why to use it. Code-only answers are not useful in the long run. Also, make sure to format your code at the top. – Mateus Jul 29 '17 at 12:58
-1

You can make a search function like this that:

const index = (array, name) => {
  // Search for the string "name" in your array
  for (let i in array){
    // Look at every element in the array, if an element has the
    // corresponding name, return its index
    if (array[i].name === name) return i;
  }
  return -1;
  // If you found nothing, return -1
}

let position = index(myArray, "John");
Alexandre Senges
  • 1,474
  • 1
  • 13
  • 22
  • Don't use `for..in` on an `Array`. – Aluan Haddad Jul 29 '17 at 12:56
  • With the new implementation of `for...in` in v8, it's actually the fastest method to do it: [V8 for...in](https://v8project.blogspot.ch/2017/03/fast-for-in-in-v8.html) – Alexandre Senges Jul 29 '17 at 13:16
  • https://stackoverflow.com/a/9329476/1915893. RE: V8 it is still awful code, also if you are going to base your rationale on the latest browser environments, use `find`. – Aluan Haddad Jul 29 '17 at 13:17
-2

Traditionally we use a constructor to build many similar objects. However, how that is OOP and is out of the scope of what you are asking.

Here we can use a for... in loop to iterate though MyArray, and check that each object does not include the name John.

function addJohn () {
for (let iterator in MyArray) { // You can also use for... of, but it will break in Node.
     if (MyArray[iterator].name == "John") {return}; //You can also replace the string with a variable name to check that all objects do not have the variable in them.
     else continue;
}
// you can now put in your new object here.
}
mount2010
  • 60
  • 1
  • 4