Home > Mobile >  JS array formatting pulling from js object
JS array formatting pulling from js object

Time:09-28

A bit of a new hobbyist and I'm working with some pre-existing code and trying to find a way to slice the array.map pull in the code instead of having it just have it write as a flat object.

Original code:

  const restructuredAttributes = {};
  jsonData.attributes.map((attr) => {
    restructuredAttributes[attr.trait_type] = attr.value;
  }, []);

The result it output into the new file is as follows:

"attributes":[
  "Attribute One":"trait one",
  "Another attribute":"Another trait",
  "And another":"And another trait"

but this is my desired result:

"attributes": [
  {
    "Attribute": "trait",
  },
  {
    "Another attribute": "Another trait",
  },
  {
    "And another": "And another trait"
  }

I have attempted to modify a bit (working on beginner knowledge, tbh) and tried to insert the {} manually as seen below:

const restructuredAttributes = {};
jsonData.attributes.map((attr) => {
  restructuredAttributes["{"   attr.trait_type] = attr.value   "}";
}, []);

but they end up inside of the "" pulled from the js object

"attributes": [
  "{Attribute One": "trait one}",
  "{Another attribute": "Another trait}",
  "{And another": "And another trait}"

Any input or guidance would be greatly appreciated.

CodePudding user response:

Return an object with a single property based on your attr value. The map method of the array returns a new array based on the result of the loop.

const restructuredAttributes = jsonData.attributes.map((attr) => ({
  [attr.trait_type]: attr.value;
}));
  • Related