简体   繁体   中英

Getting one of the object value/state inside of an array

An array of objects with 4 properties inside. I would like to get the value of the specific property inside of all the object(s) inside of that array.

Here are some codes that I used

state = {
 Controls: [{
        id: null,
        property: '',
        description: '',
        part: '',
    }]
}

getPropertyValue(){
    const  {propertyValue} = document.querySelector('#property').value;
    if (propertyValue=== 1){
        return 
             <Input>  
               <option>1</option>
               <option>2</option>;
             </Input>;
    }
    if (propertyValue === 2){
        return   
             <Input>
               <option>3</option>
               <option>4</option>
             </Input>;
    } else {
        return '';
    }
}

this is the Property Select Input inside of render()return()

  <Input
        type="select" 
        name="property" 
        id="property" 
        onChange={(e) => this.onChange(i, e.target.value, 
        'property')} value={this.getValue(i, 'property')}

        placeholder="type"
 >
  <option value="1">value 1</option>
  <option value="2">value 2</option>
   </Input>

I expect the result will display another select input once the user selected an option in the Property Select Input. The selected value in the Property Input will determine what select input will be displayed or added in the form.

--- The thing is this Property Input can be more than one (since I have an 'add button' where once it is clicked, a new Property Input will be added). I want to get all the values from the Property Input(an object property from an array). ---

You can use the array.map function to iterate through the array and return the values of any property.

getValuesOfProperty(propertyName){
return this.state.Controls.map(object => object[propertyName]);
}

// To get all the ids inside array
const ids = getValuesOfProperty('id');

// To get all the descriptions inside array
const descriptions = getValuesOfProperty('description');

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