0

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));
0

3 Answers 3

1

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));

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

Comments

0

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?

Comments

0

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))

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.