Emmathem
Emmathem

Reputation: 103

Vue.js - Convert objects to Array of Objects with a key and value

How to format this object to an array of objects

const failed = { 
  "4579043642": "Lodge with set number '4579043642' exists!",
  "4579043641": "Lodge with set number '4579043641' exists!",
  "4579043640": "Lodge with set number '4579043640' exists!",
}

to this expected output

[
  {
    "fieldName": "4579043642",
    "message": "set number '4579043642' exists!"
  },
  {
    "fieldName": "4579043641",
    "message": "set number '4579043641' exists!"
  },
  {
    "fieldName": "4579043640",
    "message": "set number '4579043640' exists!"
  }
]
data() {
  return {
    formattedList: [],
  };
},

I have tried converting using this format;

uploadFeedbackReject: {
  handler: function(newFeed) {
    if (failed) {
        this.formattedList = [response.failed];
      }
  },
  immediate: true,
  deep: true,
},

I need help.

Thanks.

Upvotes: 7

Views: 21505

Answers (3)

Daniel Pantalena
Daniel Pantalena

Reputation: 429

This works well

const failed = {
  4579043642: "Lodge with set number '4579043642' exists!",
  4579043641: "Lodge with set number '4579043641' exists!",
  4579043640: "Lodge with set number '4579043640' exists!",
};

const arrayFailed = Object.entries(failed).map((arr) => ({
  fieldName: arr[0],
  message: arr[1],
}));

console.log(arrayFailed);

Upvotes: 7

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

loop through the object fields and push an object with current property as fieldname and the value as message property :

const formerList = {
  "4579043642": "Lodge with set number '4579043642' exists!",
  "4579043641": "Lodge with set number '4579043641' exists!",
  "4579043640": "Lodge with set number '4579043640' exists!",
}

let a = []

for (f in formerList) {
  a.push({
    fieldName: f,
    message: formerList[f]
  })

}

console.log(a)

or map the object field :

const formerList = {
  "4579043642": "Lodge with set number '4579043642' exists!",
  "4579043641": "Lodge with set number '4579043641' exists!",
  "4579043640": "Lodge with set number '4579043640' exists!",
}

let a = []

a = Object.keys(formerList).map((field) => {

  return {
    fieldName: field,
    message: formerList[field]
  }
})

console.log(a)

Upvotes: 1

SpicySpices
SpicySpices

Reputation: 1

You could loop through the object with Object.keys() and take the value and name, push into an object, then push into the array.

let obj = {
  alice: "asdf",
  bob: 3,
  charles: 98.67
}

let arr = [];

for(let i=0; i<Object.keys(obj).length; i++){

  // Get the name and value of the old object
  let name = Object.keys(obj)[i];
  let value = obj[name];
  
  // Create the new object
  let newObj = {
    fieldName: name,
    message: value
  }

  // Push the new object into the array of objects
  arr.push(newObj);
}

Upvotes: 0

Related Questions