Home > OS >  Formatting the array of object
Formatting the array of object

Time:11-20

I have this data

{
  "fruits": [
    { "1": "apple" },
    { "2": "book" },
  ],
  "year": 2022
}

and want to get ['1', '2'] and ['apple', 'book'].

CodePudding user response:

I don't know how you're using that data, but it might make sense to think about restructuring the data, so that fruits is an array of the string values only, because the keys of the fruit objects don't make much sense on first view.

If you can't change the structure or don't want to, you could get the information you want to get like that:

const obj = {
  "fruits": [
    { "1": "apple" },
    { "2": "book" },
  ],
  "year": 2022
};

const numbers = obj.fruits.map(fruit => Object.keys(fruit)[0]); // ["1", "2"] 
const fruits = obj.fruits.map(fruit => Object.values(fruit)[0]); // ["apple", "book"]

To learn more about Object.keys and Object.values I'd recommend the MDN docs: keys, values

CodePudding user response:

You should know about iterations in arrays and objects. Here is an answer:

const x = { fruits: [{ 1: "apple" }, { 2: "book" }], year: 2022 };

const numbers = [];
const strings = [];

x.fruits.forEach((fruit) => {
    numbers.push(...Object.keys(fruit));
    strings.push(...Object.keys(fruit).map(f =>   fruit[f]));
})

console.log(numbers);
console.log(strings);
  • Related