简体   繁体   中英

Pushing an object to array using foreach

let inputValues = [];    
for (let i = 0; i < inputs.length; i++) {
    let inputValue = inputs[i].value;
    inputValues.push(inputValue)
}    
let newCar = {
    Model: inputValues[0],
    Brand: inputValues[1],
    Date: inputValues[2],
    Horsepower: inputValues[3],
    Transmission: inputValues[4],
    Class: inputValues[5]
}
newData.push(newCar) 

Can someone help me push newCar object to newData array using foreach loop. inputs are my inputs. i need to add the input values to my object keys. and push the object to the array. i need to do this in a way where i dont have newCar object declared like this.

There's no need for the loop or the newCar variable, you can put the object directly in the call to push()

newData.push({
    Model: inputs[0].value,
    Brand: inputs[1].value,
    Date: inputs[2].value,
    Horsepower: inputs[3].value,
    Transmission: inputs[4].value,
    Class: inputs[5].value
});

But it should work the same either way.

If we assume that your number of labels is the same as your number of inputs. Then we can do all this work in one loop as seen in the example code snippet example. Feel free to run it and see how it all works.

That being said, it is best to add your divs with the labels themselves so then you can gather the data from the divs rather than having to deal with fixed indexes which could become a problem as you add more labels.

<div data-label="Model">Toyota</div>

Then you will be able to do the below by doing this assuming inputs is an array of divs defined as above

let newData = [];    
inputs.forEach((input) => newData.push({
   [input.attr('data-label')]: input.text()
}))  

But you could shorting this even more by just using a map

let newDate = inputs.map((input) => ({
   [input.attr('data-label')]: input.text()
}))

 // This method assumes that your divs will have the same number of labels // We will assume input values are as such. But you can change it to be array of divs let inputs = [{ value: 'Corolla' }, { value: 'Toyota' }, { value: '2014' }, { value: 'coolHorsies' }, { value: 'coolTransmission' }, { value: 'coolClass' }] let labels = ['Model', 'Brand', 'Date', 'Horsepower', 'Transmission', 'Class']; let newData = []; inputs.forEach((input, idx) => newData.push({ [labels[idx]]: input.value, })) console.log(newData)

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