0

I've data response like this

{
"data": {
  "product": {
    "colors": ["#3498db", "#00ccff"],
    "items": [
     {
       "label": "Phone",
       "value": "23.00"
     },
     {
       "label": "Notebook",
       "value": "3.00"
     }
    ]
   }
 }
}

and then i want push the colors inside items

expected: items have three(3) variable each of index

items: [
 {
  label: phone,
  value: 23.00,
  color: #3498db
 }
]

i've try using push and concat but i got error "Cannot read property 'data' of undefined"

here my code

generaliseData(dashboardC) {
  let genData = Object.assign({}, dashboardC)
    if (genData.product.items.length > 0) {
      for (let i of genData.product.items) {
        i.value = parseInt(i.value)
          for (let j of genData.product.colors) {
            i = i.push(j)
          }
       }
      console.log(genData)
    }
 }
2
  • label: phone, Is that a new variable, or did you mean for that to be a string? (I'm assuming color needs to be a string too, and JS doesn't keep trailing zeros as in value) Commented Oct 31, 2018 at 7:53
  • @CertainPerformance new variable inside items[i] Commented Oct 31, 2018 at 7:55

3 Answers 3

1

You can use map to iterate through your list, expect to have the length of colors equal the length of item

const response = {
"data": {
  "product": {
    "colors": ["#3498db", "#00ccff"],
    "items": [
     {
       "label": "Phone",
       "value": "23.00"
     },
     {
       "label": "Notebook",
       "value": "3.00"
     }
    ]
   }
 }
};
function addColorToItem(response) {
  const product = response.data.product;
  const colors = product.colors;
  const items = product.items;
  
  return items.map((item, index) => {
    item.color = colors[index];
    return item;
  })
}

console.log(addColorToItem(response));

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

Comments

0

You could iterate items and assign a color.

var response = { data: { product: { colors: ["#3498db", "#00ccff"], items: [{ label: "Phone", value: "23.00" }, { label: "Notebook", value: "3.00" }] } } },
    temp = response.data.product;

temp.items.forEach((o, i) => o.color = temp.colors[i]);

console.log(response);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

You can use a simple forEach() loop for that result:

var data = {
  "product": {
    "colors": ["#3498db", "#00ccff"],
    "items": [{
        "label": "Phone",
        "value": "23.00"
      },
      {
        "label": "Notebook",
        "value": "3.00"
      }
    ]
  }
};
data.product.items.forEach((item, index) => item.color = data.product.colors[index]);
console.log(data);

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.