1

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:

  • loop through each element in a list
  • create a dict from the name/path of that element
  • append the dict to a list

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?

2
  • 1
    So your example input list is not a valid javascript object (the [ user1: {...}, ...] one), so is that a typo?. And for your side question, yes you can absolutely do that. Commented Feb 24, 2018 at 1:16
  • [ user1: {name: 'ben'}, user2: {path: 'none'}] is not a valid array. Commented Feb 24, 2018 at 1:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I'd also add that JavaScript doesn't really have 'Dictionaries' - but Objects that can act like them.
is newObject.items the same as state.items (as seen in the op) ?
Yes. You can name the references whatever you want, but I chose to use newObject to be clear. You can look at your console to see the object. The problem is probably upstream though.... instead of fixing the problem afterward - consider eliminating the source of the problem.

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.