2
var originalArray = [
      {Name: "IPHONE8s", Id: 4}, 
      {Name: "Iphone 9", Id: 5}, 
      {Name: "IPHONEX", Id: 6}
];

how to change it to be something like this

var changeArray = [
      {text: "IPHONE8s", value: 4 },
      {text: "Iphone 9", value: 5 },
      {text: "IPHONEX", value: 6 }
]

Thank you very much.

1
  • Please remove your comment and replace the new code line to your post. You can doing this, by click on the edit link underneath your post. Commented Aug 17, 2018 at 11:16

5 Answers 5

3

Use Array.map()

var originalArray = [
      {Name: "IPHONE8s", Id: 4}, 
      {Name: "Iphone 9", Id: 5}, 
      {Name: "IPHONEX", Id: 6}
];

var changeArray = originalArray.map(data => ({text: data.Name, value: data.Id}))

console.log(changeArray);

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

Comments

1

You can use .map() with Object destructuring:

let data = [
  {Name: "IPHONE8s", Id: 4},
  {Name: "Iphone 9", Id: 5},
  {Name: "IPHONEX", Id: 6}
];

let result = data.map(({Name:text, Id:value}) => ({text, value}));

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

References:

Comments

0

Example code

function renameKeys(obj, newKeys) {
  const keyValues = Object.keys(obj).map(key => {
    const newKey = newKeys[key] || key;
    return { [newKey]: obj[key] };
  });
  return Object.assign({}, ...keyValues);
}

And use it like:

const obj = { a: "1", b: "2" };
const newKeys = { a: "A", c: "C" };
const renamedObj = renameKeys(obj, newKeys);
console.log(renamedObj)

Comments

0

You could map the objects by mapping the key value pairs with a new name by using an object for the keys and their new name for replacement.

This proposal preserves other properties.

var array = [{ Name: "IPHONE8s", Id: 4, foo: 'bar' }, { Name: "Iphone 9", Id: 5 }, { Name: "IPHONEX", Id: 6 }],
    replace = { Name: 'text', Id: 'value' },
    result = array.map(o => Object.assign(...Object
        .entries(o)
        .map(([k, v]) => ({ [replace[k] || k]: v }))
    ));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0
var originalArray = [{Name: "IPHONE8s", Id: 4}, {Name: "Iphone 9", Id: 5}, {Name: 
"IPHONEX", Id: 6} ];
let changeArray = []
for (let i = 0; i < originalArray.length; i++) {
  let tmpObj = {}
  tmpObj.text = originalArray[i].Name
  tmpObj.value = '' + originalArray[i].Id
  changeArray.push(tmpObj) 
}
console.log(changeArray)

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.