簡體   English   中英

嘗試從對象數組中刪除鍵

[英]Trying to remove keys from array of objects

我有一個帶有一組對象的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); 

您可以先從數組中過濾掉所有非空值,然后使用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) 

您可以使用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]; }); } }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM