在Javascript中修改对象?

时间:2014-12-11 21:38:37

标签: javascript node.js object

我有一个以下类型的对象:

{ 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 }

我想通过这个对象重申一下,并修改它只保留contextids name等于某个字符串(例如thingsToLearn)的方式。

从原始对象中删除不需要的上下文有什么好方法?

谢谢!

2 个答案:

答案 0 :(得分:1)

循环,检查,拼接:

var nameToKeep = "someId";
for (var i = 0; i < data.contextids.length; i++) {
    if (data.contextids[i].name != nameToKeep) {
        data.contextids.splice(i, 1);
        i--;
    }
}

答案 1 :(得分:0)

听起来像是Array.filter的工作:

&#13;
&#13;
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));
&#13;
&#13;
&#13;