-5

I have data like

const data = {
  Name : "Apple",
  Weight : 5,
  Address : "Somewhere",
  Contact : 777666,
  X : 908,
  Y : 562,
}

and another array of data as

const arrData = ["Name","Weight"];

Now I need a new data of object in a variable that has key equal to array of data. For example required data is

newData = [
  {Name : "Apple"},
  {Weight: "5"},
]
  • Show us what you have tried. SO isn't a free code writing service. The objective here is for you to post your attempts to solve your own issue and others help when they don't work as expected. See [ask] and [mcve] – charlietfl Jun 02 '21 at 12:48
  • Hint: you need to loop over `arrData` and set each property of an object. You can use `reduce` or a simple loop for that. – Yury Tarabanko Jun 02 '21 at 12:49
  • `console.log(["Name","Weight"].reduce((a,b)=>(data[b]&&(a[b]=data[b]),a),{}))` – Lawrence Cherone Jun 02 '21 at 12:58

2 Answers2

0

Looking for this?

const data = { Name : "Apple", Weight : 5, Address : "Somewhere", Contact : 777666, X : 908, Y : 562, }

const arrData = ["Name","Weight"];

// Define a new object that holds your result
const result = {};

// Loop trought every key using `.forEach` (can also be done using while/for loop)
// ... and writing a new property to result (using e as key and data[e] as value)
arrData.forEach(e => result[e] = data[e]);
console.log(result)

Or even as one-liner:

const data = {
  Name: "Apple",
  Weight: 5,
  Address: "Somewhere",
  Contact: 777666,
  X: 908,
  Y: 562,
}

const result = (o={},["Name", "Weight"].map((e, v)=>o[e]=data[e] ), o);
console.log(result)
stacj
  • 1,103
  • 1
  • 7
  • 20
-1

const data = {
  Name: "Apple",
  Weight: 5,
  Address: "Somewhere",
  Contact: 777666,
  X: 908,
  Y: 562,
}
const arrData = ["Name", "Weight"];
let newData = {};
arrData.forEach(x => {
  newData[x] = data[x]
})

console.log(newData);
Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Amir Saadallah
  • 668
  • 1
  • 8
  • 19