尝试从对象数组中删除键

时间:2019-07-18 07:21:26

标签: javascript arrays object

我有一个带有一组对象的Javascript数组,我试图删除该数组中每个对象的键(即0和1),但是我正努力寻找Javascript函数可以解决问题。

[{
    '0': {
      id: '630640',
      stuff: 'name1',
      anotherProp: 'prop1'
    },
    '1': {
      id: '630640',
      stuff: 'name2',
      anotherProp: 'prop2'
    },
    id: '630640'
  },
  {
    '0': {
      id: '694969',
      stuff: 'name3',
      anotherProp: 'prop3'
    },
    id: '694969'
  },
  undefined
]

我尝试了以下操作,但没有删除键。

var keys = Object.keys(input),
  output = [];
for (var i = 0, length = keys.length; i < length; ++i)
  output.push(input[keys[i]]);
  
console.log(output);

2 个答案:

答案 0 :(得分:1)

您可以先从数组中过滤掉所有非空值,然后使用Object.values获取每个对象的值

let input = [{
	'0': {
		id: '630640',
		stuff: 'name1',
		anotherProp: 'prop1'
	},
	'1': {
		id: '630640',
		stuff: 'name2',
		anotherProp: 'prop2'
	},
	id: '630640'
},
{
	'0': {
		id: '694969',
		stuff: 'name3',
		anotherProp: 'prop3'
	},
	id: '694969'
},
undefined
];

let output = input.filter(nonNull => nonNull).map(obj => Object.values(obj));
console.log(output)

答案 1 :(得分:0)

您可以使用Object.values来获取object的所有值。如果您还希望支持较旧的浏览器,则可以使用Object.keys自己映射值。

var input = JSON.parse(`[{"0":{"id":"630640","stuff":"name1","anotherProp":"prop1"},"1":{"id":"630640","stuff":"name2","anotherProp":"prop2"},"id":"630640"},{"0":{"id":"694969","stuff":"name3","anotherProp":"prop3"},"id":"694969"},null]`);

console.log(input.filter(Boolean).map(function(item) {
  return Object.values(item);
}));

您也可以尝试使用以下格式:{630640: [{},{}], 634969: [{}]}

var input = JSON.parse(`[{"0":{"id":"630640","stuff":"name1","anotherProp":"prop1"},"1":{"id":"630640","stuff":"name2","anotherProp":"prop2"},"id":"630640"},{"0":{"id":"694969","stuff":"name3","anotherProp":"prop3"},"id":"694969"},null]`);

console.log(input.filter(Boolean).reduce(function(result, item) {
  result[item.id] = Object.values(item).filter(function(property) {
    return typeof property === "object" && property;
  });
  return result;
}, {}));

或此格式:[{id:630640, list: [{},{}]},{id:634969, list: [{}]}]

var input = JSON.parse(`[{"0":{"id":"630640","stuff":"name1","anotherProp":"prop1"},"1":{"id":"630640","stuff":"name2","anotherProp":"prop2"},"id":"630640"},{"0":{"id":"694969","stuff":"name3","anotherProp":"prop3"},"id":"694969"},null]`);

console.log(input.filter(Boolean).map(function(item) {
  return {
    id: item.id,
    list: Object.values(item).filter(function(property) {
      return typeof property === "object" && property;
    })
  };
}));

如果要支持较旧的浏览器支持,可以像这样填充Object.values

Object.defineProperty(Object, "values", {
  configurable: false,
  writable: false,
  value: function(obj) {
    return Object.keys(obj).map(function(key) {
      return obj[key];
    });
  }
});