0

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: "[email protected]",
            phone: "123-123-1234",
            owner: "Drath",
            street: "Gin Blvd",
            city: "Austin",
            country: "USA",
            duns:"123112321",
            type: "buyer"
        },
        {
            name: "Asus", // -->COMPANY NAME
            email: "[email protected]",
            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);

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. It works! What code should I use if I need the new names it to an existing companies array["Apple","Samsung"]; instead of an empty []; array?
3

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);

1 Comment

I tried this. Doesn't work. In the listbox, i need 2 options: Huawei and Asus. But this code puts both the names in a single option like: "Huawei, Asus" I need individual list options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.