0

Let's say there is an object:

var obj = {
    filed1: {
    id: 'first',
    order: 3,
    rules: {
        required: true,
        minlength: 5
    }
  },
  filed2: {
    id: 'second',
    order: 2,
    rules: {
        required: true
    }
  },
  filed3: {
    id: 'third',
    order: 1,
  }
}

I want to create an array which will contain the id of object who has required property. So, in this case the array will be:

['first', 'second']

How to do this?

var obj = {
    filed1: {
    id: 'first',
    order: 3,
    rules: {
        required: true,
        minlength: 5
    }
  },
  filed2: {
    id: 'second',
    order: 2,
    rules: {
        required: true
    }
  },
  filed3: {
    id: 'third',
    order: 1,
  }
}

var arr = [];

/*for (key in obj) {
  if obj.hasOwnProperty(required) {
    var ids = 
    arr.push(ids);
  }
}*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

2

2 Answers 2

3

Get all the values of obj using Object.values. Then you can just use filter and map to get the desired result.

You can also use reduce to do this in a single loop.

var obj = {
  filed1: {
    id: 'first',
    order: 3,
    rules: {
      required: true,
      minlength: 5
    }
  },
  filed2: {
    id: 'second',
    order: 2,
    rules: {
      required: true
    }
  },
  filed3: {
    id: 'third',
    order: 1,
  }
};

const result = Object.values(obj)
  .filter(val => (val.rules || {}).required)
  .map(val => val.id);

console.log(result);

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

Comments

0

I strongly recommend suggestion provided by Sebastian Simon. But If you are looking for something copy paste, please use following function. Pass your object as function parameter.

function getRequiredIds(obj) {
  var ids = [];
  for (var key in obj) {
    if (obj[key]["rules"] && obj[key]["rules"]["required"])
      ids.push(obj[key]["id"]);
  }
  return ids;
}

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.