1

Can anyone tell me how to do this? I want to change the Product* value be a key/value pair (Product: Product*) and each one to be its own object.

Input:

[
  "ProductA": {
    "Available": true,
    "Customers": "non-registered"
  },

  "ProductB": {
    "Number": 0
  },

  "ProductC": {
    "Number": 10,
    "Available": false,
    "Customers": "registered"
  }
]

Desired Output:

[
  {
    "Product": "ProductA",
    "Available": true,
    "Customers": "non-registered"
  },
  {
    "Product": "ProductB",
    "Number": 0
  },
  {
    "Product": "ProductC",
    "Number": 10,
    "Available": false,
    "Customers": "registered"
  }
]
1
  • 1
    note that your desired output is impossible, it's not valid json or a valid object: the outer object must be an array if you want to have unnamed objects in it Commented Feb 6, 2020 at 22:46

3 Answers 3

1

Assuming you want the resulting objects in an array, you can do this with a simple .map() using Object.keys():

const data = { "ProductA": { "Available": true, "Customers": "non-registered" }, "ProductB": { "Number": 0 }, "ProductC": { "Number": 10, "Available": false, "Customers": "registered" } };

let result = Object.keys(data).map(key => ({Product: key, ...data[key]}));
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

You can use Object.entries to get the key value pair, and then map it to match to your desired output properties.

var prod = {
  "ProductA": {
    "Available": true,
    "Customers": "non-registered"
  },

  "ProductB": {
    "Number": 0
  },

  "ProductC": {
    "Number": 10,
    "Available": false,
    "Customers": "registered"
  }
};

const mappedProduct = Object.entries(prod).map(([key, value]) => {
  return {
    product: key,
    ...value
  }
});

console.log(mappedProduct);

1 Comment

With arrow functions implicit return you can shorten your map function to: ([key, value]) => ({ product: key, ...value })
0

Simple solution, without requiring Object.entries

const obj = {
  "ProductA": {
    "Available": true,
    "Customers": "non-registered"
  },

  "ProductB": {
    "Number": 0
  },

  "ProductC": {
    "Number": 10,
    "Available": false,
    "Customers": "registered"
  }
}

const res = Object.keys(obj).map(key => ({
  Product: key,
  ...obj[key]
}))
console.log(res)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.