1

What I would like to do is to process JSON data and store each object after getting out of the for loop. However, the obj gets updated every iteration, so the objectArray holds only David's information in each element in it. I would like the objArray to hold each of the processed JSON objects (screenshot below). The JSON process is to store search a userId and name and store them in the objectArray. Could someone help me figure out how I could store each object in the objectArray? Thank you in advance.

const obj = {};
var objectArray = [];
var data = [
    {
        "userId": "123",
        "name": "John",
        "phoneNumber": "123-456-6789"
    },
    {
        "userId": "345",
        "name": "Summer",
        "phoneNumber": "535-631-9742"
    },
    {
        "userId" : "789",
        "name": "David",
        "phoneNumber": "633-753-1352"
    }
]

var dataLen = data.length;
var people = data;

createKeyValue = ((key, value) => {
    var temp = {};
    temp["value"] = value;
    obj[key] = temp;
});


while (dataLen > 0) {
    for (let [key, value] of Object.entries(data[0])) {
        switch(key) {
            case 'userId':
                createKeyValue(key, value);
                break;
            case 'name':
                createKeyValue(key, value);
                break;
            default:
        }
    }
    
    objectArray.push(obj);
    data.shift();
    dataLen -= 1;

    
}

enter image description here

  • 1
    `data` is already an array of people objects. What do you want to be different about the new array? – Sean Aug 11 '20 at 15:12
  • 1
    I don't quite follow your question. Would you be able to edit/update it so you can show what the desired outcome is? – Karl Taylor Aug 11 '20 at 15:13
  • What should be happening here? At the moment you're adding *the same* object `obj` multiple times to the same array. So you get `objArray` which contains literally the same object (not duplicates) multiple times. – VLAZ Aug 11 '20 at 15:16
  • `obj` is keeping the attributes by reference, not by value – Emanoel Carlos Aug 11 '20 at 15:16

3 Answers3

0

You can do this using a simple forEach() loop to create and push new objects to the objArray array.

const data = [
  {
    "userId": "123",
    "name": "John",
    "phoneNumber": "123-456-6789"
  },
  {
    "userId": "345",
    "name": "Summer",
    "phoneNumber": "535-631-9742"
  },
  {
    "userId": "789",
    "name": "David",
    "phoneNumber": "633-753-1352"
  }
];

let objArray = [];

data.forEach(person => {
  objArray.push({
    userId: { value: person.userId },
    name: { value: person.name }
  });
});

console.log(objArray);
Sean
  • 6,873
  • 4
  • 21
  • 46
0

As said by our friends Kevin B and Zcoop98, its more appropriate to use forEach function, not map function:

data.forEach(elem => {
    objectArray.push({
        userId: { value: elem.userId },
        name: { value: elem.name }
    });
})
0

The error you're seeing is because of a concept in JavaScript (and programming in general) known as "passing by reference."
Objects in JS, instead of being passed as whole groups of data, are passed around as addresses to where that data is stored. This saves a lot of overhead, since objects can become quite large.

In your case however, you're running into one of the ways it can trip you up. Since obj is really getting passed by reference instead of value, you're really .pushing 3 copies of the same address (of obj) onto objectArray rather than 3 distinct sets of data.

A better approach to this problem would be using a JS Array function called map(). This function is probably best explained by MDN:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

You can use it on your data array like this:

var objectArray = [];
var data = [{
    "userId": "123",
    "name": "John",
    "phoneNumber": "123-456-6789"
  },
  {
    "userId": "345",
    "name": "Summer",
    "phoneNumber": "535-631-9742"
  },
  {
    "userId": "789",
    "name": "David",
    "phoneNumber": "633-753-1352"
  }
]

objectArray = data.map(dataEl => ({
  userId: {
    value: dataEl.userId,
  },
  name: {
    value: dataEl.name,
  },
}));

console.log(objectArray);
.as-console-wrapper {
  max-height: 100% !important;
}
zcoop98
  • 2,590
  • 1
  • 18
  • 31