david
david

Reputation: 6785

how to programmatically create dictionaries in js using a simple for loop

I need to programmatically create dicts with 'name' and 'path' key values and store them in the items list

const state = {
  items: [
    {
      name: user.name,
      path: user.path,
    },
    {
      name: user.name,
      path: user.path,
    },
  ]
}

The example above is all I'm trying to do here, its just that I need to be able to programmatically create the dicts inside the list.

To break this down into steps, I believe what I need to do is:

I am coming from a Python background so not completely sure how to do this in .js and these steps may not be correct.

The most important part, is that I need the structure above to remain as this is being called/ingested by another js module

Assuming we have a list that looks something like this:

[ user1: {name: 'ben'}, user2: {path: 'none'}]

What would be the cleanest way to loop through this and create the main example above ?

Also side question for bonus points, can I just create a list named somelistname and append the dictionaries to the list and then do

const state = {
  items: somelistname
}

would that be the same thing as my example?

Upvotes: 1

Views: 113

Answers (1)

sheriffderek
sheriffderek

Reputation: 9043

There are lots of ways to do this, but I'll do it like this for one example, and maybe it will help clarify the real purpose.

/*
var data = [
  user1: {
    name: 'ben'
  },
  user2: {
    path: 'none'
  },
];

This isn't valid...
*/

// if it's a string though...
var strangeString = "[ user1: {name: 'ben'}, user2: {path: 'none'}]";

var arrayFromString = strangeString.slice(1, -1).split(',');
// would cut off the first and last character - and then break it up in to pieces by the comma an put that into an array

console.log(arrayFromString);

var newObject = {}; // create the object... 
newObject.items = []; // create an array in that object

// loop through the array with the forEach method
arrayFromString.forEach( function(currentValue, index, fullArray) {
  currentValue = currentValue.trim();
  var user = {
    name: currentValue.name
  }
  newObject.items.push(user); // keep adding to the items array
});

console.log( newObject );
console.log( JSON.stringify(newObject) );

And that could all be one function that took in a string... but I'm guessing what you have could be adjusted to make more sense. You can look at .map() too.

https://jsfiddle.net/sheriffderek/xLgbqy4q

But, maybe you actually have an object - and not a broken array?

// no bueno
// [ user1: {name: 'ben'}, user2: {path: 'none'}]

var exampleArray = [ // if this were already an array - you wouldn't be asking this question...
  {
    id: 1,
    name: 'Ben',
    slug: 'ben',
    alive: true,
  },
  {
    id: 2,
    name: 'Sheriff Derek',
    slug: 'sheriff-derek',
    alive: true,
  },
];

var exampleObject = { // but maybe you are getting an object...
  user1: {
    id: 1,
    name: 'Ben',
    slug: 'ben',
    alive: true,
  },
  user2: {
    id: 2,
    name: 'Sheriff Derek',
    slug: 'sheriff-derek',
    alive: true,
  },
};


var newObject = {};
newObject.items = [];

for (var key in exampleObject) {
  if (exampleObject.hasOwnProperty(key)) {
    var item = {
      id: exampleObject[key].id,
      name: exampleObject[key].name,
      slug: exampleObject[key].slug,
    };
    newObject.items.push(item);
  }
}

console.log(newObject);

https://jsfiddle.net/sheriffderek/bue2vco5/

in the 2015 (newer version) of JavaScript there are new methods that make this much easier, so you can look up iterators and keys.

Upvotes: 1

Related Questions