0

The end result needs to look something like this:

Name1: "John"
Name2: "Johnson"
Age: "30"
City: "Atlanta"
State: "GA"

I'm trying to push objects into a single object, but what its doing is creating an array with multiple objects that I can't make a single call ( like if I wrapped all the data above in variable newData, I could just call newData[0] and it would return the above ). Currently, I'm trying it like this:

var newData = [];
$(data).each(function (i, value) {
    var getTitle = $(value).attr('data-title'); // Returns title
    var getData = $(value).val();
    newData.push({ getTitle : getData });
});

This code produces a result like:

0:{ getTitle : "John" }
1:{ getTitle : "Johnson" }
2:{ getTitle : "30" }
3:{ getTitle : "Atlanta" }
4:{ getTitle : "State" }

So not sure what I'm doing wrong.

1 Answer 1

1

It doesn't seem like you want an array at all, but rather just an object.

var newData = {};

$(data).each(function (i, value) {
    var getTitle = $(value).attr('data-title'); // Returns title
    var getData = $(value).val();
    newData[getTitle] = getData;
});
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah I tried the object route, but couldn't figure out how to mash it into one
The syntax on the last line will either update a property of the object if it finds it, or if not, it will add it. The end result should be a single object (newData) with your items in it.
Awesome, this works great. Thanks for saving me more time than I've already spent on it. Will check mark it when i can.

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.