简体   繁体   中英

Javascript - How to add multiple objects into an empty array

I am trying to add multiple objects- Company Names into listBox Companies. I used $scope.companies.push(newCompany[0].name); to add the company into the list. But only the first object's company gets added because I used newCompany[0].name .

Now, how do I add the second company name into the list without entering newCpmpany[1].name ? Say there are 50 companies, I cannot add all 50 by doing this. Is there a better way to add all the names in one go? like a loop or incrementing the element or something? Looking for some help. Thanks in advance.

 var newCompany = [{ name: "Huawei", // -->COMPANY NAME email: "Drath@yahoo.com", phone: "123-123-1234", owner: "Drath", street: "Gin Blvd", city: "Austin", country: "USA", duns:"123112321", type: "buyer" }, { name: "Asus", // -->COMPANY NAME email: "Vadar@yahoo.com", phone: "999-123-8888", owner: "Vadar", street: "Vince Blvd", city: "Dallas", country: "USA", duns: "123100000", type: "supplier" }]; window.localStorage.setItem("newCompany", JSON.stringify(newCompany)); 

 $scope.companies = []; var newCompany = JSON.parse(localStorage.getItem("newCompany")); $scope.companies.push(newCompany[0].name); 

You can try with spread

$scope.companies.push(...newCompany.map(item => item.name));

or why do you need exactly push? why don't you just init $scope.companies with exact values

var newCompany = JSON.parse(localStorage.getItem("newCompany"));
$scope.companies = newCompany.map(item => item.name)

If spread is not supported just a regular splice of array can be used

var names = newCompany.map(function(company){return company.name});
$scope.companies.splice(-1, 0, names);

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