简体   繁体   中英

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) 在此处输入图片说明

As the image shows, a child component consists of elements like, input[type=range], input[type=number], dropdown menu, etc

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. 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.

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. (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. (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 .

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