Home > Mobile >  How can I update some array entries to have multiple values?
How can I update some array entries to have multiple values?

Time:10-25

I have an array as such:

   arr = {
      name: 1,
      address: 1,
      phone: 2,
      email: 5,
   };

I want to be able to add further information to this array, eg:

       arr = {
          name: 1 true,
          address: 1 false,
          phone: 2 true,
          email: 5 true,
       };
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I've tried a few different things like:

arr.email[2] = true;

With no results (or errors).

Is there a way to do this? Or a better way of handling this issue?

CodePudding user response:

I'm not entirely certain what you're going for here since you mention wanting an array ([]) but what you've shown in your question is an object ({}), but if I'm reading right you can accomplish this with an object where each key holds an array of values. That would look like:

const obj = {
  name: [1],
  address: [1],
  phone: [2],
  email: [5],
};

obj.email.push(true);
obj.email.push("whatever");

console.log(obj)
console.log(obj.email[1])
console.log(obj.email[2])
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

So obj is an object, but name, address, phone, and email are all arrays which you can extend as needed with array methods.

CodePudding user response:

Original data structure doesn't allow you to add data the way you want. So you have to create the object with needed data structure at first. After this the original data should be moved to the new object and only after this you can add some new data.

     newObj.name.push(origObj.name,true,"something1","something2");
     newObj.address.push(origObj.address,false);
     newObj.phone.push(origObj.phone,true);
     newObj.email.push(origObj.email,true);

output

{
"name":[1,true,"something1","something2"],
"address":[1,false],
"phone":[2,true],
"email":[5,true]
}

original object

    var origObj = {
        name: 1,
        address: 1,
        phone: 2,
        email: 5
    };

new object

    var newObj = {
        name: [],
        address: [],
        phone:[],
        email: []
    };

CodePudding user response:

You would need to assign a variable to your array and call a function...that way, each element could be classified (boolean, string, integer, etc.) For example,

const fruit = ['banana', 'apple', 'pear'];
console.log(fruit);   
  • Related