0

I have a bit JSON object with over 50 keys like

const data = {a:1, b:2, c:3,....,y:99,z:100}

and 2 arrays containing keys of this json object

const arr1 = ["a", "b", "m", "l", "x", "y", "Z"]
const arr2 = ["c", "d", "g", "h", "i", "k", "q"]

Now I want to copy all the value from data object into 2 new objects which contain only data of those keys which are present in arr1 and arr2 into 2 objects

user1592129
  • 461
  • 1
  • 5
  • 16

3 Answers3

1

const data = { a: 1, b: 2, c: 3, d: 4, y: 99, z: 100 };

const arr1 = ['a', 'b', 'm', 'l', 'x', 'y', 'Z'];
const arr2 = ['c', 'd', 'g', 'h', 'i', 'k', 'q'];

const res1 = arr1.map(item => ({ [item]: data[item] }));
const res2 = arr2.map(item => ({ [item]: data[item] }));

console.log(res1);
console.log(res2);
michael
  • 4,053
  • 2
  • 12
  • 31
1

Maybe you can try, is very easy and there are a lot of ways to do.

var valuesFromArr1 = arr1.map(key => data[key]);
David
  • 923
  • 8
  • 19
  • OP wants 2 objects with the keys from 2 arrays. Not a value array – adiga Dec 28 '20 at 10:18
  • "Now I want to copy all the value from data object into 2 new objects which contain only data of those keys which are present in arr1 and arr2 into 2 objects". "which contain only data" – David Dec 28 '20 at 10:24
0

If you want all your keys in a single object, consider using an Array reduce method. Here I abstracted it into a reusable function and applied it to each of your desired arrays.

const data = {a:1, b:2, c:3, y:99, z:100};

const arr1 = ["a", "b", "c"];
const arr2 = ["c", "y", "z"];

function arrToData(arr, data) {
  return arr.reduce((acc, el) => {
    acc[el] = data[el];
    return acc;
  }, {});
}

console.log(
  arrToData(arr1, data),
  arrToData(arr2, data)
);
Nick
  • 16,066
  • 3
  • 16
  • 32