admin管理员组

文章数量:1289525

I have an array objArray. I want to make a function so that it will check if there is another object with the same name key. If it exists, it will add +1 in the qty key. If the object doesn't exist, it will push the new object to the array.

var objArray = [
  {"name":"bike","color":"blue","qty":2},
  {"name":"boat","color":"pink", "qty":1},
];

var carObj = {"name":"car","color":"red","qty":1};
var bikeObj = {"name":"bike","color":"blue","qty":1};
  
function checkAndAdd (obj) {
    for (var i = 0; i < objArray.length; i++) {
      if (objArray[i].name === obj.name) {
          objArray[i].qty++;
          break;
      }
      else {
          objArray.push(obj);
      }
    };
}

checkAndAdd(carObj);

console.log(objArray);

checkAndAdd(bikeObj);

console.log(objArray);

I have an array objArray. I want to make a function so that it will check if there is another object with the same name key. If it exists, it will add +1 in the qty key. If the object doesn't exist, it will push the new object to the array.

var objArray = [
  {"name":"bike","color":"blue","qty":2},
  {"name":"boat","color":"pink", "qty":1},
];

var carObj = {"name":"car","color":"red","qty":1};
var bikeObj = {"name":"bike","color":"blue","qty":1};
  
function checkAndAdd (obj) {
    for (var i = 0; i < objArray.length; i++) {
      if (objArray[i].name === obj.name) {
          objArray[i].qty++;
          break;
      }
      else {
          objArray.push(obj);
      }
    };
}

checkAndAdd(carObj);

console.log(objArray);

checkAndAdd(bikeObj);

console.log(objArray);

After checkAndAdd(carObj);

console.log(objArray);

Should give

[
  {"name":"car","color":"red", "qty":1},
  {"name":"bike","color":"blue","qty":2},
  {"name":"boat","color":"pink", "qty":1},
]

And fter checkAndAdd(bikeObj);

console.log(objArray);

Should give

[
  {"name":"car","color":"red", "qty":1},
  {"name":"bike","color":"blue","qty":3},
  {"name":"boat","color":"pink", "qty":1},
]

Thanks in advance!

Share Improve this question edited Sep 22, 2021 at 16:57 isherwood 61.1k16 gold badges120 silver badges169 bronze badges asked Apr 11, 2018 at 17:13 Joe82Joe82 1,2513 gold badges28 silver badges41 bronze badges 1
  • @D.Pardal it actually took me a few minutes to undesrstand that as well, as OP didn't make it clear. It seems that when a car is pushed, the quantity ends up being 2 instead of 1 – VLAZ Commented Apr 11, 2018 at 17:21
Add a ment  | 

5 Answers 5

Reset to default 2

You need to check all objects and exit the function if one item is found for incrementing the quantity.

If not found push the object.

var objArray = [{ name: "bike", color: "blue", qty: 2 }, { name: "boat", color: "pink", qty: 1 }],
    carObj = { name: "car", color: "red", qty: 1 },
    bikeObj = { name: "bike", color: "blue", qty: 1 };
  
function checkAndAdd (obj) {
    for (var i = 0; i < objArray.length; i++) {
        if (objArray[i].name === obj.name) {
            objArray[i].qty++;
            return;                             // exit loop and function
        }
    }
    objArray.push(obj);
}

checkAndAdd(carObj);
console.log(objArray);

checkAndAdd(bikeObj);
console.log(objArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }

The problem is that you're push()ing inside the loop, instead of returning immediately once found and only call push() outside the loop.

A cleaner approach would be:

function checkAndAdd(obj) {
    var matchingObj = objArray.find(o => o.name === obj.name);

    if (matchingObj)
        matchingObj.qty++;
    else
        objArray.push(obj);
}

You can also use find to search for the object property.

Using Object.assign before pushing the object will clone the object and will not change the original object when you change the qty (If you add more object with the same name.)

var objArray = [
    {"name":"bike","color":"blue","qty":2},
    {"name":"boat","color":"pink", "qty":1},
];

var carObj = {"name":"car","color":"red","qty":1};
var bikeObj = {"name":"bike","color":"blue","qty":1};

function checkAndAdd(obj) {
  let o = objArray.find(o => o.name === obj.name);  //Find if name exist

  if (!o) objArray.push(Object.assign({},obj));     //If not exist, push. 
  else o.qty += obj.qty;                            //If exist, add the qty
}

checkAndAdd(carObj);
console.log(objArray);

checkAndAdd(bikeObj);
console.log(objArray);

Use findIndex to find in objArray if the object exist.If it does then update the object else push the new object

var objArray = [{
    "name": "bike",
    "color": "blue",
    "qty": 2
  },
  {
    "name": "boat",
    "color": "pink",
    "qty": 1
  },
];

var carObj = {
  "name": "car",
  "color": "red",
  "qty": 1
};
var bikeObj = {
  "name": "bike",
  "color": "blue",
  "qty": 1
};

function checkAndAdd(obj) {
  var x = objArray.findIndex(function(item) {
    return item.name === obj.name;

  });
  if (x === -1) {
    objArray.push(obj)
  } else {
    objArray[x].qty = objArray[x].qty + obj.qty
  }
}

checkAndAdd(carObj);
checkAndAdd(bikeObj);
console.log(objArray);

Simple enough:

function checkAndAdd(obj) {
for (var i=0; i < objArray.length; i++) {
    if (objArray[i]name === obj.name) {
        objArray[i].qty++;
        return
    }
}
objArray.push(obj)
}

Explanation:

Your function was pushing each time the object name didn't match. Instead, when this function a matching name, it incrementes the qty and stops and then if the loops ends without any match, it pushes the obj.

本文标签: javascriptHow can I check if object exists in array of objects and update quantityStack Overflow