1

I have one array like:

arr = ['AD','CI','AI']

and I have one object like

{ 
  "AD": "Mailing Address",
  "CI": "Additional Interest",
  "HO": "Homeowners",
  "AI": "Additional Interest"
}

Here the object contains the key value pair and form the array key how to compare that key into the object and get the value of that key. How to get the value of array key from the object ?

1
  • Was the answer helpful? Commented Aug 15, 2018 at 14:26

3 Answers 3

2

Use Array.forEach() to loop over the array and get the value from the object:

var arr = ['AD','CI','AI'];
var obj = {"AD": "Mailing Address","CI": "Additional Interest","HO":"Homeowners","AI": "Additional Interest"};
arr.forEach(key => console.log(obj[key]));

If you want to use that value further inside the loop then make it multi-line like:

var arr = ['AD','CI','AI'];
var obj = {"AD": "Mailing Address","CI": "Additional Interest","HO":"Homeowners","AI": "Additional Interest"};
arr.forEach((key) => {
  //some processing here
  console.log(obj[key]);
});

Use map() to get the array of those values:

var arr = ['AD','CI','AI'];
var obj = {"AD": "Mailing Address","CI": "Additional Interest","HO":"Homeowners","AI": "Additional Interest"};
var res = arr.map((key) => obj[key]);
console.log(res);

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

Comments

1

This one-liner will give you an array result containing the values from the object.

let result = arr.map(a=>obj[a]);

Comments

1

is the array needed in your case? if you just want the values of the object you can do this:

const obj = { 
  "AD": "Mailing Address",
  "CI": "Additional Interest",
  "HO": "Homeowners",
  "AI": "Additional Interest"
};

Object.entries(obj).forEach(([key, value]) => console.log(`${key}: ${value}`));

or

const obj = { 
  "AD": "Mailing Address",
  "CI": "Additional Interest",
  "HO": "Homeowners",
  "AI": "Additional Interest"
};

Object.keys(obj).forEach((key) => console.log(`${obj[key]}`));

Hopefully that is helpful!

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.