简体   繁体   English

通过在 javascript 中重新格式化来减少数组

[英]Reduce a array with reformatting in javascript

I want to reduce the array with only the subject being present in the new object.我想减少数组,只有新的 object 中存在主题。

array = [{
    subject: "maths",
    credits: 3
  },
  {
    subject: "chemistry",
    credits: 2,
    lab: {
      lab: "chemistry_lab",
      lab_credits: 1,
    },
  }
]

the new object is reformatted and its values are assigned as strings.新的 object 被重新格式化,其值被分配为字符串。 What's the best way to achieve this实现这一目标的最佳方法是什么

const subject = {
  maths: "",
  chemistry: "",
  chemistry_lab: "",
};

Here's how I tried this but it returns an array of objects, but I want this to be a single object as above这是我尝试过的方法,但它返回一个对象数组,但我希望这是一个如上所述的单个 object

const sub = array.map((op) => {
  const container = {};
  container[op.subject] = "";
  return container;
});

Your map method is the right idea, however, it doesn't map the lab objects.您的 map 方法是正确的想法,但是,它不是 map lab对象。 You could go for an approach that uses .flatMap() to build an array of [key, value] pairs from each object in your array.您可以 go 使用.flatMap()从数组中的每个 object 构建[key, value]对的数组。 By flat-mapping, you can take each subject and lab (if it exists) and "convert" the object into two arrays of key values.通过平面映射,您可以获取每个主题和实验室(如果存在)并将 object “转换”为两个 arrays 键值。 You can then filter this mapped array to remove any [key, value] pairs where the key is a falsy value (ie: undefined), and then use Object.fromEntries() on your array of [key, value] pair arrays to build an object for you.然后,您可以过滤此映射数组以删除键为假值(即:未定义)的任何[key, value]对,然后在 [ key [key, value]对 arrays 的数组上使用Object.fromEntries()来构建一个 object 给你。

 const array = [{ subject: "maths", credits: 3 }, { subject: "chemistry", credits: 2, lab: { lab: "chemistry_lab", lab_credits: 1, }, } ]; const res = Object.fromEntries(array.flatMap(obj => [ [obj.subject, ''], [obj.lab?.lab, ''] ]).filter(([key]) => key)); console.log(res);

Another option could be to remove the .filter() , and perform a check in your .flatMap() function before adding the lab [key, value] pair.另一种选择是删除.filter() ,并在添加实验室[key, value]对之前检查.flatMap() function。 This will help you avoid doing an additional iteration on your array:这将帮助您避免对数组进行额外的迭代:

 const array = [{ subject: "maths", credits: 3 }, { subject: "chemistry", credits: 2, lab: { lab: "chemistry_lab", lab_credits: 1, }, } ]; const res = Object.fromEntries(array.flatMap( obj => obj.lab?.lab? [[obj.subject, ''], [obj.lab.lab, '']]: [[obj.subject, '']] )); console.log(res);

Lastly, a way using .reduce() could look something like this.最后,使用.reduce()的方法可能看起来像这样。 It builds up an object, adding the subject as a key using computed property names and will add the lab if it exists.它构建了一个 object,使用计算的属性名称将主题添加为键,如果存在则添加实验室。 It uses the spread syntax to spread the result of curr.lab?.lab && {[curr.lab.lab]: ''} .它使用传播语法传播curr.lab?.lab && {[curr.lab.lab]: ''}的结果。 When cur.lab.lab results in a truthy value, the object is spread and merged into the returned object literal:当 cur.lab.lab 结果为真值时,object 被传播并合并到返回的 object 文字中:

 const array = [{ subject: "maths", credits: 3 }, { subject: "chemistry", credits: 2, lab: { lab: "chemistry_lab", lab_credits: 1, }, } ]; const res = array.reduce((obj, curr) => ({...obj, [curr.subject]: '', ...(curr.lab?.lab && {[curr.lab.lab]: ''}) }), {}); console.log(res);

 let array = [{ subject: "maths", credits: 3 }, { subject: "chemistry", credits: 2, lab: { lab: "chemistry_lab", lab_credits: 1, }, } ] let subject = {} array.forEach(el => { subject[el.subject] = "" if (el.lab) { subject[el.lab.lab] = "" } }) console.log(subject) // output // { maths: "", chemistry: "", chemistry_lab: "" }

 var array = [ { subject: "maths", credits: 3 }, { subject: "chemistry", credits: 2, lab: { lab: "chemistry_lab", lab_credits: 1, }, } ]; var p = array.reduce((acc,i)=>{ acc[i.subject]= ''; if(i.lab){ acc[i.lab.lab]='' } return acc; },{}) console.log(p)

You can also use JavaScript reduce to achieve the same.您也可以使用 JavaScript reduce来实现相同的效果。

Here's snippet you can try:这是您可以尝试的片段:

var p = array.reduce((acc,i)=>{
acc[i.subject]= '';
if(i.lab){
  acc[i.lab.lab]=''
}
return acc;
},{})

console.log(p)

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

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