I was trying to combine first name last name in an object and return same object again
I have tried multiple ways with map and foreach but doesn't seem to work
[ { "id": 1321, "createdAt": "2022-08-03T12:36:20.096Z", "UpdatedAt": "2022-08-03T12:36:20.096Z", "firstName": "g", "lastName": "prashanth", "zipCode": "39493", "NPI": "990343" }, { "id": 1322, "createdAt": "2022-08-03T12:36:20.096Z", "UpdatedAt": "2022-08-03T12:36:20.096Z", "firstName": "prasilla", "lastName": "shaik", "zipCode": "39493", "NPI": "990343" } ]
what i have tried:
let final_array: any=[]
data.forEach(function (value: any, a:any) {
let obj: any={}
console.log(a)
final_array.push( obj[keys_array[a]] = data[a]["firstName"] " " data[a]["lastName"], obj[keys_array[a]] =data[a]["zipCode"], obj[keys_array[a]]=data[a]["NPI"])
})
});
required format:
[ { "name": "g prashanth", "zipCode": "39493", "NPI": "990343" }, { "Name": "prasilla shaik", "zipCode": "39493", "NPI": "990343" } ]
CodePudding user response:
const newArrayOfObj = array.map((obj) => {
let temp = { ...obj, name: `${obj.firstName} ${obj.lastName}` };
let res = {};
for (const [key, value] of Object.entries(temp)) {
if (key === "firstName" || key === "lastName") continue;
else res[key] = value;
}
return res;
});
CodePudding user response:
var data = [ { "id": 1321, "createdAt": "2022-08-03T12:36:20.096Z", "UpdatedAt": "2022-08-03T12:36:20.096Z", "firstName": "g", "lastName": "prashanth", "zipCode": "39493", "NPI": "990343" }, { "id": 1322, "createdAt": "2022-08-03T12:36:20.096Z", "UpdatedAt": "2022-08-03T12:36:20.096Z", "firstName": "prasilla", "lastName": "shaik", "zipCode": "39493", "NPI": "990343" } ]
// console.log( final_array)
let data_1= data.map((object,i) => {
return {...object, fullName: data[i]["firstName"] ' ' data[i]["lastName"]} ;
});
You need to pass index value i to map, and probably also include the fullname construction inside the map. Also the outer loop is not required
CodePudding user response:
if you want full result with added property full name you try @Anuja script.
this script will work as the ouput you mentioned.
const dataAsJson = `[ { "id": 1321, "createdAt": "2022-08-03T12:36:20.096Z", "UpdatedAt": "2022-08-03T12:36:20.096Z", "firstName": "g", "lastName": "prashanth", "zipCode": "39493", "NPI": "990343" }, { "id": 1322, "createdAt": "2022-08-03T12:36:20.096Z", "UpdatedAt": "2022-08-03T12:36:20.096Z", "firstName": "prasilla", "lastName": "shaik", "zipCode": "39493", "NPI": "990343" } ]`;
const data = JSON.parse(dataAsJson);
const changedData = data.map(item => ({ name: `${item.firstName} ${item.lastName}`
, zipCode: item.zipCode
, NPI: item.NPI }));
console.log(changedData);