0

I have an object of the following kind:

{ body: { entry: { body: '' }, context: '' },
  contextids: 
   [ { uid: 'ff992fa0-817a-11e4-bea0-299f5e3c3819',
       name: 'deemeetreesNotebook' },
     { uid: 'ff992fa1-817a-11e4-bea0-299f5e3c3819', name: 'public' },
     { uid: 'ff992fa2-817a-11e4-bea0-299f5e3c3819', name: 'ideas' },
     { uid: 'ff992fa3-817a-11e4-bea0-299f5e3c3819',
       name: 'thingsToLearn' },
     { uid: 'ff992fa4-817a-11e4-bea0-299f5e3c3819',
       name: 'wayToRussia' },
     { uid: 'ff992fa5-817a-11e4-bea0-299f5e3c3819',
       name: 'polysingularity' },
     { uid: 'ff992fa6-817a-11e4-bea0-299f5e3c3819',
       name: 'infranodus' },
     { uid: 'ff992fa7-817a-11e4-bea0-299f5e3c3819',
       name: 'artmital' } ],
  internal: 1 }

I want to reiterate through this object, and modify it in the way that it only keeps the contextids where name equals a certain string (e.g. thingsToLearn).

What is a good way to remove unwanted contextids from my original object?

Thanks!

3
  • 1
    Use Array#filter. Commented Dec 11, 2014 at 21:40
  • ^ that, contextids is an array ! Commented Dec 11, 2014 at 21:41
  • jsfiddle.net/0hjc7dgL Commented Dec 11, 2014 at 21:43

2 Answers 2

1

Loop, check, splice:

var nameToKeep = "someId";
for (var i = 0; i < data.contextids.length; i++) {
    if (data.contextids[i].name != nameToKeep) {
        data.contextids.splice(i, 1);
        i--;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

The only things I would change about this answer would be to write it functionally and write data.contextids[i].name !== nameToKeep in the if statement, because !== is best practice
0

Sounds like a job for Array.filter:

var d = {
  body: {
    entry: {
      body: ''
    },
    context: ''
  },
  contextids: [{
    uid: 'ff992fa0-817a-11e4-bea0-299f5e3c3819',
    name: 'deemeetreesNotebook'
  }, {
    uid: 'ff992fa1-817a-11e4-bea0-299f5e3c3819',
    name: 'public'
  }, {
    uid: 'ff992fa2-817a-11e4-bea0-299f5e3c3819',
    name: 'ideas'
  }, {
    uid: 'ff992fa3-817a-11e4-bea0-299f5e3c3819',
    name: 'thingsToLearn'
  }, {
    uid: 'ff992fa4-817a-11e4-bea0-299f5e3c3819',
    name: 'wayToRussia'
  }, {
    uid: 'ff992fa5-817a-11e4-bea0-299f5e3c3819',
    name: 'polysingularity'
  }, {
    uid: 'ff992fa6-817a-11e4-bea0-299f5e3c3819',
    name: 'infranodus'
  }, {
    uid: 'ff992fa7-817a-11e4-bea0-299f5e3c3819',
    name: 'artmital'
  }],
  internal: 1
};

d.contextids = d.contextids.filter(function(item) {
  return item.name === "thingsToLearn";
  });

alert(JSON.stringify(d.contextids));

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.