0

I have object which contains array, I want to filter the object based on array value.

For example:

    {
       "sun":["sleep","walk"],
       "mon":["read","dance","ride"],
       "tue":["work","dance","sleep"],
    }

if I enter keyword "sleep" then result should be as follows

    {
      "sun":["sleep"],
      "tue":["sleep"],
    }

Any suggestion would be helpful

2

4 Answers 4

1

Just iterate over the object and do the manipulations, please find working code below:

const obj = {
  "sun": ["sleep", 'walk'],
  "mon": ["read", "dance", "ride"],
  "tue": ["work", "dance", "sleep"],
}

function filterIt(filterString) {
  const result = {};
  for (const prop in obj) {
    if (obj[prop].includes(filterString)) {
      result[prop] = [filterString];
    }
  }
  return result;
}

const finalResult = filterIt('sleep');
console.log(finalResult);

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

Comments

1

Useful tools for solving this problem:

let obj =
{
  "sun": ["sleep", "walk"],
  "mon": ["read", "dance", "ride"],
  "tue": ["work", "dance", "sleep"],
};

let result = Object.fromEntries(
  Object.entries(obj)
    .filter(kvp => kvp[1].includes('sleep'))
    .map(([k, v]) => [k, v.filter(o => o === 'sleep')])
  )

console.log(result)

Comments

1

Using Object.keys, map, includes.

let obj ={
       "sun":["sleep","walk"],
       "mon":["read","dance","ride"],
       "tue":["work","dance","sleep"],
    }

let new_obj = {}
let search = 'sleep'

Object.keys(obj).map(key => {
     obj[key].includes(search) ? new_obj[key]=[search] : ''
})

console.log(new_obj)

Comments

0

You can use _.transform() to create a new object. Check if the value array (v) includes the str, and if it does assign the key with a new array that includes the str:

const fn = (obj, str) => _.transform(obj, (o, v, k) => {
  if(v.includes(str)) o[k] = [str]
})

const obj = {
  "sun":["sleep","walk"],
  "mon":["read","dance","ride"],
  "tue":["work","dance","sleep"],
}

const result = fn(obj, 'sleep')

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>

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.