2

i want to push my retrieved results which is an inline string result to my array object item

Here is my code :

  arrayObject.push({ type: "type", item: itemArray });

  arrayObject.forEach((elementItem) => {
    global.forEach((element) => {
      const { items } = element;
      for (const item in items) {
        const title = items[item].title;
        elementItem.item.push({ title });
      }
    });
  });

And here is my json file that i retrieve from global, items and title

  global: [
    {
      items: {
        xxx: {
          title: 'result1',
        }
      },
    }
 ]

The result i want is like this :

[ { type: 'xxx', item: [ {name: result1 } ] } ]
10
  • 6
    what is global? what is collectionObject? Commented Mar 4, 2019 at 11:19
  • @JosefKatič same results Commented Mar 4, 2019 at 11:23
  • 1
    your code doesnt make sense you havent supplied everything Commented Mar 4, 2019 at 11:24
  • 1
    please supply them. so we know whats going on you shouldnt need 3 nested loops to achieve what you want Commented Mar 4, 2019 at 11:29
  • 1
    @JoeWarner i just updated my question Commented Mar 4, 2019 at 11:36

1 Answer 1

0

Here i've used reduce and object.values to produce your expected outcome.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

const global = [{
    way: 'type1',
    items: {
      get: {
        title: 'result1',
      },
      post: {
        title: 'result2',
      },
      put: {
        title: 'result3',
      },
    },
  },
  {
    way: 'type2',
    items: {
      get: {
        title: 'test1',
      },
      post: {
        title: 'test2',
      },
      put: {
        title: 'test3',
      },
    },
  },
]

function mapJsonToTypes(arr) {
  const typeAndTitles = (acc, {items, way: type}) => {
    return [...acc, {type, item: getTitlesFromItems(items)}]
  }

  return arr.reduce(typeAndTitles, []);
}

function getTitlesFromItems(items = {}) {
  return Object.values(items).map(({ title }) => title)
}



console.log(mapJsonToTypes(global));

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

1 Comment

awesome whack that like if it helped :) have a nice day.

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.