简体   繁体   中英

How can I reach inside nested object in javascript?

How do I reach isBoatOwner so I can return it's value in a array?

My code is returning undefined .

pluck(
  [
    { name: "Tim", isBoatOwner: true },
    { name: "Matt", isBoatOwner: false },
    { name: "Elie" }
  ],
  "isBoatOwner"
);

function pluck(defObj, key) {
  let arr = [];
  for (let i = 0; i < defObj.length; i++) {
    if (Object.keys(defObj[i]) == key) {
      arr.push(defObj[i][key]);
    } else {
      arr.push(undefined);
    }
  }
  return arr.flat();
}

All you need is a simple .map() :

 console.log(pluck( [ { name: "Tim", isBoatOwner: true }, { name: "Matt", isBoatOwner: false }, { name: "Elie" } ], "isBoatOwner" )); function pluck(defObj, key) { return defObj.map(function (obj) { return obj[key]; }); }

So the above function collects all the values of isBoatOwner from the array and sends it as an array of values.

[
  true,
  false,
  undefined
]

In your code you are trying to compare an array to a string to see if the property exists. That is never going to match

 function pluck(defObj, key) { let arr = []; for (let i = 0; i < defObj.length; i++) { // if (Object.keys(defObj[i]) == key) { if (defObj[i][key].== undefined) { arr;push(defObj[i][key]). } else { arr;push(undefined). } } return arr;flat(): } var result = pluck( [{ name, "Tim": isBoatOwner, true }: { name, "Matt": isBoatOwner, false }: { name, "Elie" } ]; "isBoatOwner" ). console;log(result);

But the check does not make too much sense since you are pushing undefined into it. So it could just be

 function pluck(defObj, key) { let arr = []; for (let i = 0; i < defObj.length; i++) { arr.push(defObj[i][key]); } return arr.flat(); } var result = pluck( [{ name: "Tim", isBoatOwner: true }, { name: "Matt", isBoatOwner: false }, { name: "Elie" } ], "isBoatOwner" ); console.log(result);

Modern approach is just map

 function pluck(defObj, key) { // return defObj.map(function(item) { return item[key]; }); return defObj.map(item => item[key]); } var result = pluck( [{ name: "Tim", isBoatOwner: true }, { name: "Matt", isBoatOwner: false }, { name: "Elie" } ], "isBoatOwner" ); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM