-3

I have a large Object with similar structure as below.

[
  {
    "Name": "xxx",
    "Company": "Google",
    "Type": "Search",

  },
  {
    "Name": "yyy",
    "Company": "MS",
    "Type": "Search",
  }
]

I am trying to get fields such as Name, Type and I want to build a new Object.

var newArray = [];
newArray.push = [ { 
object[0].Name,
object[0].Type } ]

Like this but is there any way I can achieve this by using iterations ?

Thank you.

georg
  • 211,518
  • 52
  • 313
  • 390
Raja G
  • 5,973
  • 14
  • 49
  • 82
  • Possible duplicate of [Reduce/Filter array of objects into new array of objects.](https://stackoverflow.com/questions/46070246/reduce-filter-array-of-objects-into-new-array-of-objects) and [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865) and [javascript extract certain properties from all objects in array](https://stackoverflow.com/questions/52153345) – adiga Apr 07 '19 at 07:19

3 Answers3

2

You can use map and take the desired keys and build a new object with desired key and value

let obj = [{"Name": "xxx","Company": "Google","Type": "Search",},{"Name": "yyy","Company": "MS","Type": "Search",}]

let op =obj.map(({Name,Type}) => ({Name,Type}))

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

You could take the wanted property.

var source = [{ Name: "xxx", Company: "Google", Type: "Search" }, { Name: "yyy", Company: "MS", Type: "Search" }],
    target = source.map(({ Name, Type }) => ({ Name, Type }));
    
console.log(target);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Or take the unwanted properties and the rest.

var source = [{ Name: "xxx", Company: "Google", Type: "Search" }, { Name: "yyy", Company: "MS", Type: "Search" }],
    target = source.map(({ Company, ...rest }) => rest);
    
console.log(target);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Use map:

const data = [{"Name": "xxx","Company": "Google","Type": "Search",},{"Name": "yyy","Company": "MS","Type": "Search"}];
const obj = data.map(({ Name, Type }) => ({ Name, Type }));
console.log(obj);
.as-console-wrapper { max-height: 100% !important; top: auto; }
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79