[英]Push new object into a multidimensional array
說我有這個數組:
var array = [{'ref1': {'Product': 'Car', 'color': 'Red'}}, {'ref2': {'product': 'velo', 'color': 'red'}}]
我只想在'ref1'上添加'price':'8'
如何正確執行此操作?
亞歷克斯
如果您不確定不確定包含“ ref1”屬性的對象是否始終位於索引0,則可以使用以下動態代碼:
const insert = (idProp, key, value) => {
var el = array.find(el => el.hasOwnProperty(idProp));
if (el) { el[idProp][key] = value }
}
然后通過
insert('ref1', 'Price', 8)
這是您的操作方式: array[0]['ref1'].price = 8;
var array = [ {'ref1': {'Product': 'Car', 'color': 'Red'}}, {'ref2': {'product': 'velo', 'color': 'red'}}] array[0]['ref1'].price = 8; console.log(array)
觀察:REF1有一個屬性Product
,同時REF2有一個屬性product
小寫。 稍后可能會給您帶來一些問題。
您可以執行以下操作:
var arr = [{'ref1': {'Product': 'Car', 'color': 'Red'}}, {'ref2': {'product': 'velo', 'color': 'red'}}]; console.log(arr); arr[0]['ref1'].Price = 8; console.log(arr);
查找ref1項的索引,然后將該值分配給Price參數。
var array = [{'ref1': {'Product': 'Car', 'color': 'Red'}}, {'ref2': {'product': 'velo', 'color': 'red'}}];
var ref1 = array.filter(item => item == {'ref1': {'Product': 'Car', 'color': 'Red'}})[0];
var index = array.indexOf(ref1);
array[index]['Price'] = 8;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.