marjan
marjan

Reputation: 77

return object item if array values matches the the object keys

I have an object and an array. I want to check array values and if array values match the object keys and return its values in an new object.

var obj = {
 "active": 12,
 "inactive": 14
 "neutral": 16
}

var arr1=[12]

  function getKeys(obj, arr) {
   return arr.map(v => {
   const foundTuple = Object.entries(obj).find(x => x[1] === v);
   return foundTuple ? foundTuple[0] : null;
 });
}


 console.log(getKeys(obj, arr1));


// it logs ["active"]

I want this function to output object key instead of object value

 if   var arr1=['active','inactive']
 it should log
  var newObj = {
    "active": 12,
    "inactive": 14
  }

Upvotes: 0

Views: 225

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386560

Just filter the keys and map the pairs for a new object.

const
    object = { active: 12, inactive: 14, neutral: 16 },
    keys = ['active', 'inactive'],
    result = Object.fromEntries(keys
        .filter(key => key in object)
        .map(key => [key, object[key]])
    );

console.log(result);

Step by step

const
    object = { active: 12, inactive: 14, neutral: 16 },
    keys = ['active', 'inactive'],
    result = {};

for (const key of keys)
    if (object.hasOwnProperty(key))
        result[key] = object[key];

console.log(result);

Upvotes: 1

minhazmiraz
minhazmiraz

Reputation: 452

You can follow this:

var obj = {
    "active": 12,
    "inactive": 14,
    "neutral": 16
 };

var arr1 = ["active", "inactive"];

Object.keys(obj).filter(
  key => arr1.includes(key)
).reduce(
  (newObj, key) => ({...newObj, [key]: obj[key]})
  , {}
);

Know more about map and reduce.

Upvotes: 0

mgm793
mgm793

Reputation: 2066

You can use a normal for loop with the entries:

  const obj = {
    active: 12,
    inactive: 14,
    neutral: 16
  };
  const arr1 = ["active", "inactive"];
  const newObj = {};
  const entries = Object.entries(obj);
  for (let i = 0; i < entries.length; ++i) {
    const [key, value] = entries[i];
    if (arr1.includes(key)) newObj[key] = value;
  }
  console.log(newObj);

Upvotes: 1

lukaasz555
lukaasz555

Reputation: 174

var obj = {
 "active": 12,
"inactive": 14,
"neutral": 16
 }

var arr1=[12]

const getKeyByVal = (obj, val) => {
    return Object.keys(obj).find(k => obj[k] === val);
}

const checkArray = arr => {
    return arr.map((ar) => getKeyByVal(obj, ar));
}

console.log(checkArray(arr1));

Upvotes: 1

Related Questions