Casey
Casey

Reputation: 2719

Access nested javascript object

I have a dynamic form element that I want to save using ajax. I formatted the data as a javascript object, and am trying to update each of the elements. But I'm having trouble accessing a nested element so I can set a new value. The result from below is 'undefined' but I want to do is look up an item from they array by number, so I can update the qty value.

// object to hold form data for ajax submit
var jsonLoad = {
    type: 'estimate',
    note: null,
    terms: null,
    tax: 0,
    items: [
        {
            1 :
            {
                description: 'test123',
                rate: 300,
                qty: 1
            }
        },
        {
            2 :
            {
                description: 'test555',
                rate: 600,
                qty: 2
            }
        }
    ]
};

function getItem(i) {
    jsonLoad.items.forEach(function (element) {
        if ( element[i] === i ) {
            return(element[i]);
        }
    });
}

console.log(getItem(2));

Upvotes: 0

Views: 76

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386868

You could check an item with the given property and return that item.

Array#some stops iteration if the callback returns a truthy value.

function getItem(key) {
    var item;
    jsonLoad.items.some(function (object) {
        return item = object[key];
    });
    return item;
}

var jsonLoad = { type: 'estimate', note: null, terms: null, tax: 0, items: [{ 1: { description: 'test123', rate: 300, qty: 1 } }, { 2: { description: 'test555', rate: 600, qty: 2 } }] };

console.log(getItem(2));

Upvotes: 1

Tudor Ilisoi
Tudor Ilisoi

Reputation: 2944

Here's your answer:

// object to hold form data for ajax submit
var jsonLoad = {
    type: 'estimate',
    note: null,
    terms: null,
    tax: 0,
    items: [
        {
            1 :
            {
                description: 'test123',
                rate: 300,
                qty: 1
            }
        },
        {
            2 :
            {
                description: 'test555',
                rate: 600,
                qty: 2
            }
        }
    ]
};

function getItem(i) {
  var ret = null;
    jsonLoad.items.forEach(function(item){
      if(item[i]){ //if the item object has the numeric key "i"
        ret = item[i];
      }
    })
  return ret;
}

console.log(getItem(2));

Here's a more literate way of checking if the key exists: if(Object.keys(item).includes(i))

Upvotes: 0

coderz
coderz

Reputation: 4999

element[i] === i is not working, you should check whether i is a key existing in element, replace it with i in element. More about check whether a key exists in an object please see Checking if a key exists in a JavaScript object?

Upvotes: 0

Related Questions