简体   繁体   中英

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.

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)

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);

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM