简体   繁体   English

map 在复杂的 javascript 对象数组上获取值

[英]map over complex javascript array of objects to get values

I have a big document that shows nutrition data of a dummy recipe.我有一个大文件,显示了一个虚拟食谱的营养数据。

Look at the codesandbox json first先看codeandbox json

i want to get total calories and nutrition facts of this object;我想得到这个 object 的总卡路里和营养成分;

recipe has an array of stuffs and in stuffs array we have 2 item objectes; recipe 有一个东西数组,在 stuffs 数组中我们有 2 个项目对象;

each item has fact ( facts );每个项目都有事实(facts);

facts are ( vitamins, nutrition, calories and others )事实是(维生素、营养、卡路里和其他)

each fact has value;每个事实都有价值;

I tried many nested array.map high order function, for example i got calories of each item, but problem was that nested map function returns each calorie value in a seperate array... I tried many nested array.map high order function, for example i got calories of each item, but problem was that nested map function returns each calorie value in a seperate array...

i want to push values of each item(recipe stuff item) in arrays like this:我想像这样在 arrays 中推送每个项目(食谱项目)的值:

const vitaminValues = []
const nutritionValues = []
const caloriesValues = []
const othersValues = []

if i get this, i can get total calories, vitamins, nutrition and others information如果我得到这个,我可以获得总卡路里、维生素、营养和其他信息

but idk, if u guys have any better ideas just help me:) thanks但是 idk,如果你们有更好的想法,请帮助我:) 谢谢

this is JSON file of sample recipe: https://codesandbox.io/s/relaxed-brown-zrxnr?fontsize=14&hidenavigation=1&theme=dark这是示例配方的 JSON 文件: https://codesandbox.io/s/relaxed-brown-zrxnr?fontsize=14&hidenavigation=1&theme=dark

let data=//your json
let vitaminValues = [];
let nutritionValues = [];
let caloriesValues = [];
let othersValues = [];
let vitaminAValues = [];

function getValuesFromJson(obj, Arr) {
  Object.entries(obj).map(
    vitamin => vitamin[1].hasOwnProperty("value") && Arr.push(vitamin[1].value)
  );
}
data.map(d =>
  d.stuffs.map(stuff =>
    stuff.item.fact.map(f => {
      getValuesFromJson(f.vitamins, vitaminValues);
      getValuesFromJson(f.others, othersValues);
      caloriesValues.push(f.calories);
      f.nutritions.map(nutri => getValuesFromJson(nutri, nutritionValues));
      vitaminAValues.push(f.vitamins.A.value);
    })
  )
);
console.log("vitaminValues", vitaminValues);
console.log("nutritionValues", nutritionValues);
console.log("othersValues", othersValues);
console.log("caloriesValues", caloriesValues);
console.log("vitaminAValues", vitaminAValues);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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