skip to Main Content

I am using NodeJs to create my own API based from Twitter API.
The problem is that:
I have this array of object from Twitter API. It looks something like this.

[
  {
    ...
    text: "100% I am sleeping ...",
    user: {
       screen_name: "Ninja",
    },
    ...
  },
  {},
  ...
]

I want know how can I take each “text” and “screen_name” form the list above and store it in a new array of object, to look like this:

[
  {
    text: "",
    screen_name: ""
  },
  {},
  {},
  ...
]

2

Answers


  1. Use Array.map

    let arr = [{text: "100% I am sleeping ...",user: {screen_name:"Ninja"}}];
    
    let result = arr.map(({text, user : {screen_name}}) => ({text, screen_name}));
    
    console.log(result);
    Login or Signup to reply.
  2. Use array map method. This will return a new array of objects having desired keys

    var api = [{
        text: "100% I am sleeping ...",
        user: {
          screen_name: "Ninja",
        },
        somOtherVal: 'otherVal1'
    
      },
      {
        text: "100% I am sleeping ...",
        user: {
          screen_name: "Ninja",
        },
        somOtherVal: 'otherVal'
      }
    ]
    
    let newApi = api.map(function(item) {
      return {
    
        text: item.text,
        screen_name: item.user.screen_name
      }
    
    });
    console.log(newApi)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search