1

I've a json like below

[
 {
 "name": "Item",
 "attribute_list": [
 {
 "name": "Attribute 1",
 "value_list": [
 {
 "value": "1"
 },
 {
 "value": "2"
 }
 ]
 },
 {
 "name": "Attribute 2",
 "value_list": [
 {
 "value": "10"
 },
 {
 "value": "60"
 },
 {
 "value": "80"
 }
 ]
 }
 ]
 }
]

I want to change format like below

[
 {
 "Item": [{
 "Attribute 1": "1", "Attribute 2": "10"
 }]
 }
]

What I've done already:

results.map(items => {
 data[items.name.toLowerCase().replace(/ /g, '_')] = items.attribute_list?
 items.attribute_list.reduce(
 (obj, item) => Object.assign(obj, { [item.name.toLowerCase().replace(/ /g, '_')]: item.value_list?item.value_list[0].value:null }), {})
 :null
})

Thanks in advance

asked Oct 21, 2020 at 6:20

1 Answer 1

4

If I understood everything correctly, you can do it like this:

const input = [
 {
 "name": "Item",
 "attribute_list": [
 {
 "name": "Attribute 1",
 "value_list": [
 {
 "value": "1"
 },
 {
 "value": "2"
 }
 ]
 },
 {
 "name": "Attribute 2",
 "value_list": [
 {
 "value": "10"
 },
 {
 "value": "60"
 },
 {
 "value": "80"
 }
 ]
 }
 ]
 }
];
const result = input.map((entry) => {
 return {
 [entry.name]: [entry.attribute_list.reduce((res, curr) => {
 res[curr.name] = curr.value_list[0].value;
 return res;
 }, {})]
 };
});
console.log(result);

answered Oct 21, 2020 at 6:26
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.