maxspan
maxspan

Reputation: 14137

Extracting Data from an object in javascript

I am having a object called ItemData which consists of other properties. I would like to extract only the numbered items from it. below is the body of ItemData. I have tried using map but it throws error says ItemData is an object. I can use item[0] and item[1] but there are going to be many arrays in the object. Is there a structure way to extract 0 and 1 items.

ItemData

{
  0: { "daysIn": "2", "daysOut": "3", "category": "Day Shift" },
  1: { "daysIn": "5", "daysOut": "6", "category": "Day Shift" },
  type: "Fixed Multiple", 
  Status: "Active"
}

Upvotes: 1

Views: 944

Answers (4)

chaimm
chaimm

Reputation: 400

you can turn it into an array and loop through it to return what you want. I would use reduce since you can customize what and how you return the data.

Object.keys(ItemData).reduce((accumlated, current) => {
    if (Number(current)) {
        accumlated[current] = ItemData[current];
    }
    return accumlated
}, {});

this will return an object consisting of only the properties that are numbered.

if you would like it returned in an array you can just change the initial value for the reduce

Object.keys(ItemData).reduce((accumlated, current) => {
    if (Number(current)) {
        accumlated.push(ItemData[current]);
    }
    return accumlated
}, []);

Upvotes: 0

Alan Omar
Alan Omar

Reputation: 4217

let obj={0:{daysIn:"2",daysOut:"3",category:"Day Shift"},1:{daysIn:"5",daysOut:"6",category:"Day Shift"},type:"Fixed Multiple",Status:"Active"};

let result = Object.entries(obj)
              .filter(e => Number.isInteger(+e[0]))
              .map(([_,v]) => v)
              
              
console.log(result)

Upvotes: 0

Faizan Shaikh
Faizan Shaikh

Reputation: 3

Try this....

var obj = {
      0: { "daysIn": "2", "daysOut": "3", "category": "Day Shift" },
      1: { "daysIn": "5", "daysOut": "6", "category": "Day Shift" },
      type: "Fixed Multiple", 
      Status: "Active"
    }
    var result = Object.keys(obj).map((key) => [key, obj[key]]);
    
    console.log(result);

Upvotes: 0

crashmstr
crashmstr

Reputation: 28563

You don't have an array, but you can iterate over the keys that are numbers and build an array of those values.

const ItemData = {
  0: {
    "daysIn": "2",
    "daysOut": "3",
    "category": "Day Shift"
  },
  1: {
    "daysIn": "5",
    "daysOut": "6",
    "category": "Day Shift"
  },
  type: "Fixed Multiple",
  Status: "Active"
}

function getArray(obj) {
  const result = [];
  const keys = Object.keys(obj);
  for (const k of keys) {
    if (Number(k) == k) {
      result[k] = obj[k];
    }
  }
  return result;
}

const arr = getArray(ItemData);
console.log(arr);

Upvotes: 4

Related Questions