1

I wrote these two functions that maps and filter flat objects properties:

var mapObject = (obj, f, ctx) => {
  ctx = ctx || this;
  var result = {};
  Object.keys(obj).forEach(function(k) {
    result[k] = f.call(ctx, obj[k], k, obj);
  });
  return result;
};
var filterObject = (obj, f, ctx) => {
  ctx = ctx || this;
  Object.keys(obj).filter(v => {
    return (!f.call(ctx, obj[v], v, obj))
  }).forEach(v => {
    delete obj[v];
  })
  return obj;
}

These two functions can map "flat" properties (i.e. non nested objects) of and object or can filter non nested object properties in this way:

var mapObject = (obj, f, ctx) => {
  ctx = ctx || this;
  var result = {};
  Object.keys(obj).forEach(function(k) {
    result[k] = f.call(ctx, obj[k], k, obj);
  });
  return result;
};
var filterObject = (obj, f, ctx) => {
  ctx = ctx || this;
  Object.keys(obj).filter(v => {
    return (!f.call(ctx, obj[v], v, obj))
  }).forEach(v => {
    delete obj[v];
  })
  return obj;
}

console.log(mapObject({
  name: "james",
  surname: "joyce"
}, (v, k) => v.toUpperCase()))

console.log(filterObject({
  name: "james",
  surname: "joyce"
}, (v, k) => k != "name"))

console.log(mapObject(filterObject({
  name: "james",
  surname: "joyce"
}, (v, k) => k != "name"), (v, k) => v.toUpperCase()))

How to efficiently apply this to nested objects i.e. objects having objects properties?

1 Answer 1

1

I think a more efficient way to apply this to nested objects is recursion, as an example:

const mapObject = (obj, f, ctx) => {
    ctx = ctx || this;
    var result = {};
    Object.keys(obj).forEach(function(k) {
        if (typeof obj[k] === 'object' && obj[k] !== null) {
            result[k] = mapObject(obj[k], f, ctx)
        } else {
            result[k] = f.call(ctx, obj[k], k, obj);
        }
    });
    return result;
};

console.log(mapObject({
    name: "james",
    surname: "joyce",
    obj: {
        objName: "hi"
    }
}, (v, k) => v.toUpperCase()))

const filterObject = (obj, f, ctx) => {
    ctx = ctx || this;
    Object.keys(obj).filter(v => {
        if (typeof obj[v] === 'object' && obj[v] !== null) {
            filterObject(obj[v], f, ctx)
        } else {
            return (!f.call(ctx, obj[v], v, obj))
        }
    }).forEach(v => {
        delete obj[v];
    })
    return obj;
}

console.log(filterObject({
    name: "james",
    surname: "joyce",
    obj : {
        name: "objName",
        surname: "objSurname",
    }
}, (v, k) => k != "name"))

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

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.