3

Given

sessionStorage.cart = "[
  {"id":121,"name":"Pants","number":1,"specification":""},
  {"id":121,"name":"Pants","number":2,"specification":""},       
  {"id":121,"name":"Pants","number":3,"specification":""}
]"

I'd like to write a function that finds the object with id of 121, name of Pants, number of 2, so that I can update that object's specification. So I would pass the id, the name, the number, and the desired new specification value, and get an output of this:

sessionStorage.cart = "[
  {"id":121,"name":"Pants","number":1,"specification":""},
  {"id":121,"name":"Pants","number":2,"specification":"new value"},       
  {"id":121,"name":"Pants","number":3,"specification":""}
]"

Am really struggling on thinking this one through... guidance welcome!

2
  • 1
    Try to start with for and if Commented Aug 7, 2015 at 2:51
  • The question is using an array in the example, not JSON which is making the answers below incorrect. Commented Oct 27, 2018 at 14:49

5 Answers 5

5

Use this:

var cart = [
    {
        "id": 121,
        "name": "Pants",
        "number": 1,
        "specification": ""
    },
    {
        "id": 121,
        "name": "Pants",
        "number": 2,
        "specification": ""
    },
    {
        "id": 121,
        "name": "Pants",
        "number": 3,
        "specification": ""
    }
];

cart.forEach(function(entry) {
    if (entry.id == 121 && entry.name == 'Pants' && entry.number == 2) {
        entry.specification = 'new value';
    }
});

console.log(cart);

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

Comments

1

A simple solution using Array.prototype.find

sessionStorage.cart.find(e => 
  e.id     === 121     &&
  e.name   === 'Pants' &&
  e.number === 2
).specification = 'new value';

console.log(JSON.stringify(sessionStorage.cart, null, '  '));

Output

[
  {
    "id": 121,
    "name": "Pants",
    "number": 1,
    "specification": ""
  },
  {
    "id": 121,
    "name": "Pants",
    "number": 2,
    "specification": "new value"
  },
  {
    "id": 121,
    "name": "Pants",
    "number": 3,
    "specification": ""
  }
]

Note: This requires ES6.

Comments

0

You might want to try this code:

function update(oldValues, newValues, keyToCompare) {
    var keyToCompareLen = keyToCompare.length;
    var result = [];
    oldValues.forEach(function(oldValue){

        newValues.forEach(function(newValue){
            var cnt = 0;
            keyToCompare.forEach(function(key){
                if(newValue[key] == oldValue[key]) {
                    ++cnt;
                }
            });

            if(cnt == keyToCompareLen) {
                oldValue = $.extend(true, {}, oldValue, newValue);
            }
        });

        result.push(oldValue);
    });

    return result;
}

var result = update([
  {"id":121,"name":"Pants","number":1,"specification":""},
  {"id":121,"name":"Pants","number":2,"specification":""},       
  {"id":121,"name":"Pants","number":3,"specification":""}
], [
  {"id":121,"name":"Pants","number":2,"specification":"test"}
], [
  "id",
  "name",
  "number"
]);

console.log(result);

Note: You need to include the jquery library. You can also run the code here https://fiddle.jshell.net/b17fx6qk/1/

3 Comments

I think it's a little over to use jQuery for only jQuery.extend() method while you don't use it in other places.
@iplus26, No problem to that because he/she is already using a jquery library.
No, no, no. Don't get me wrong. I just want to discuss when to use jQuery... It's nothing personal, sorry...
0

Iterating through an array can be inefficient. For performance, you could stringify all of your index values and use them to store your objects in a hashmap for a quick lookup. Something like:

function cartItem() {
  this.id;
  this.name;
  this.number;
  this.specification;
}

CartItem.hash = function(id, name, number) {
  return [id, name, number].join('|');
};

cartItem.prototype.toHash = function() {
  return CartItem.hash(this.id, this.name, this.number);
};

var cartMap = cart.reduce(function(map, item) {
  var key = item.toHash();
  map[key] = item;
}, { });

Then you can (very quickly) look the item up by its hash:

cartMap[CartItem.hash(id, name, number)];

Comments

0

Try doing this. Simply match and update

$(document).ready(function() {

  var o = [];
  o.id = 121;
  o.name = "Pants";
  o.number = 2;

  updateVal(o);

});


function updateVal(o) {

  var cart = [{
    "id": 121,
    "name": "Pants",
    "number": 1,
    "specification": ""
  }, {
    "id": 121,
    "name": "Pants",
    "number": 2,
    "specification": ""
  }, {
    "id": 121,
    "name": "Pants",
    "number": 3,
    "specification": ""
  }];

  $.each(cart, function(a, b) {

    if (b.id == o.id && b.name == o.name && b.number == o.number) {
      b.specification = "new value";
    }


  });

  alert("value updated. specification:" + cart[1].specification);

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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.