简体   繁体   English

如何将值从子数组传递给父数组

[英]How to pass values from Child Array to a Parent

My requirement is as follows我的要求如下

In parent component, i am passing an array of Child Components(array can be 1 or more than 1)在父组件中,我传递了一个子组件数组(数组可以是 1 或大于 1) 在此处输入图片说明

As the image shows, a child component consists of elements like, input[type=range], input[type=number], dropdown menu, etc如图所示,子组件由诸如 input[type=range]、input[type=number]、下拉菜单等元素组成

Parent component has a button父组件有一个按钮

<button>Search Location</button>

When I click on Search button in Parent, I need the value of every single elements in each Child Component, for eg.当我点击 Parent 中的 Search 按钮时,我需要每个子组件中每个元素的值,例如。 structure can be as follows结构可以如下

let finalObj={
    child1: {
        dropValue: "Room1",
        cond: "AND"
    },
   child2: {
        inputVal: 50,
        cond: "OR"
   },
   child[n]: {
        rangeVal: 1,
        cond: ""
   }
}

Also, we can change the value again(before clicking search), and Search button should always pickup, the current set value of each component.此外,我们可以再次更改该值(单击搜索之前),并且搜索按钮应始终拾取每个组件的当前设置值。

I am not sure how to go ahead with this.我不知道如何继续这个。 Any pointers will be really helpful.任何指针都会非常有帮助。 Please help请帮忙

So you need to change an array of components into an object of... well first of all that's a .reduce use.因此,您需要将一组组件更改为...的对象。首先,这是一个.reduce使用。

const almostFinalObj = components.reduce((retval, each, i) => {
   retval['child'+i] = each;
   return retval;
}, {});

That will give an object like这将给出一个像

almostFinalObj = {
   child1: component1,
   child2: component2,
   childN: componentN,
}

Now we can .forEach through it, transforming each child component into whatever format you're looking for.现在我们可以.forEach通过它,将每个子组件转换为您正在寻找的任何格式。 (I'm unclear on that part but maybe you can figure out the rest.) (我不清楚那部分,但也许你可以弄清楚其余部分。)

Object.keys(almostFinalObj).forEach((each, i, array) => {
  let component = array[i];
  array[i] = {};
  component.querySelectorAll('input').forEach(e => {
    array[i][e.name] = e.value;
  });
});

This assumes the name attribute exists on each element in each child row-component.这假设name属性存在于每个子行组件中的每个元素上。 (As in, each radio button in your example has <input type='radio' name='cond' .... /> .) You could use id or even a data-XXX attribute as well instead of e.name . (例如,您示例中的每个单选按钮都有<input type='radio' name='cond' .... /> 。)您可以使用id甚至data-XXX属性代替e.name

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

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