1

I am having an issue getting accessing the value from a key of an object.

I am passing in this.fields which has 2 objects in an array like,

[{'First Name': 'firstName'}, {'Last Name': 'lastName'}]

I am able to get the keys using the Object.keys function, but cannot figure out how to get the values associated with them.

let properties = [];
for (let field of this.fields) {
  console.log(field);
  properties.push({
    "name": Object.keys(field),
    "value": ""
  });
}

I have tried doing this.fields[field] to get it, but it is returning undefined. Any advice on how to approach this?

1
  • 3
    Wouldn't it make more sense to have 1 object with 2 keys instead of 1 array with 2 objects each one 1 key? Commented Oct 21, 2015 at 1:19

2 Answers 2

2
let properties = [];
for (let field of this.fields) {
  for (let prop in field) {
    properties.push({ "name": prop, "value": field[prop] });
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you this works, I am assuming that I needed the 2nd for loop to go over the object once it was taken out of the array. Don't know why I didn't think of that!
Avoid hasOwnProperty when you don't need it. Your first version was much better.
1

If you have only one key/value pair, you can do:

let key = Object.keys(field)[0];
let value = field[key];

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.