访问包含对象的数组,该数组进一步包含对象

时间:2019-01-17 09:28:52

标签: javascript arrays object

我的数据是包含数组的对象,默认情况下数组还包含对象,我必须将第一个数组的第一个对象的值存储在变量中

这是我的列表

//data
object:{
 fruits:[
   {
     name:"Apple",
     color:"Red"
   },
   {
     name:"Orange",
     color:"Orange"
   }
 ],
 veggies:[
  {
    name:"Jackfruit",
    color:"Muddy"
  },
  {
   name:"Spinach",
   color:"Green"
  }
 ]
}

试图将水果第一个对象的值存储在所选变量中

Selected :object[0]

将值存储在“选定”变量中

1 个答案:

答案 0 :(得分:-1)

存储对对象的引用

const selected = object.fruits[0];

存储对象的精确副本

const selected = JSON.

const object = {
 fruits:[
   {
     name:"Apple",
     color:"Red"
   },
   {
     name:"Orange",
     color:"Orange"
   }
 ],
 veggies:[
  {
    name:"Jackfruit",
    color:"Muddy"
  },
  {
   name:"Spinach",
   color:"Green"
  }
 ]
}

const selectedRef = object['fruits'][0];
selectedRef.name = "Metal";
console.log("This is a reference!", object['fruits'][0]);

const selectedClone = JSON.parse(JSON.stringify(object['fruits'][1]));
selectedClone.name = "Metal";
console.log("This is a clone!", object['fruits'][1]);

parse(JSON.stringify(object.fruits [0]))