I want to merge two JSON data using Javascript or Jquery.
var object1 = [{
"id": 11,
"name": "Vasanth",
"username": "Vasanth.Rajendran",
"email": "vasanth#mail.com",
"address": {
"street": "Nungampakkam",
"suite": "No154",
"city": "Chennai",
"zipcode": "31428-2261",
"geo": {
"lat": "-38.2386",
"lng": "57.2232"
}
},
"phone": "024-648-3804",
"website": "google.net",
"company": {
"name": "Test",
"catchPhrase": "Centralized empowering task-force",
"bs": "target end-to-end models"
}
}];
var object2 = [{
"id": 2,
"name": "Raju",
"username": "Raju.Rajendran",
"email": "Raju#mail.com",
"address": {
"street": "Nungampakkam",
"suite": "No154",
"city": "Chennai",
"zipcode": "31428-2261",
"geo": {
"lat": "-38.2386",
"lng": "57.2232"
}
},
"phone": "024-648-3804",
"website": "google.net",
"company": {
"name": "Test",
"catchPhrase": "Centralized empowering task-force",
"bs": "target end-to-end models"
}
}];
example result:
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
}];
object1 and object2 are arrays. You can use the concat method to concatenate arrays.
newObj = object1.concat(object2);
var object1 = [{
"id": 11,
"name": "Vasanth",
"username": "Vasanth.Rajendran",
"email": "vasanth#mail.com",
"address": {
"street": "Nungampakkam",
"suite": "No154",
"city": "Chennai",
"zipcode": "31428-2261",
"geo": {
"lat": "-38.2386",
"lng": "57.2232"
}
},
"phone": "024-648-3804",
"website": "google.net",
"company": {
"name": "Test",
"catchPhrase": "Centralized empowering task-force",
"bs": "target end-to-end models"
}
}];
var object2 = [{
"id": 2,
"name": "Raju",
"username": "Raju.Rajendran",
"email": "Raju#mail.com",
"address": {
"street": "Nungampakkam",
"suite": "No154",
"city": "Chennai",
"zipcode": "31428-2261",
"geo": {
"lat": "-38.2386",
"lng": "57.2232"
}
},
"phone": "024-648-3804",
"website": "google.net",
"company": {
"name": "Test",
"catchPhrase": "Centralized empowering task-force",
"bs": "target end-to-end models"
}
}];
var newObject = object1.concat(object2);
console.log(newObject);
Try this:
var newObj = [object1[0], object2[0]];
OR
var newObj = object1.concat(object2);
concat creates a new array consisting of the elements in the object on
which it is called, followed in order by, for each argument, the
elements of that argument (if the argument is an array) or the
argument itself (if the argument is not an array).
Reference: Array.prototype.concat()
They are arrays as I can see. You can do:
var object3 = object1.concat(object2);
//you can access your objects like this: object3[0] and object3[1]
//Or in for loop
for (i=0; i<object3.length; i++) {
console.log(object3[i]);
}
Otherwise for objects you can check
How can I merge properties of two JavaScript objects dynamically?
For reference:
var array = [] // this is array
var theObject = {} // json object
if you want to merge them into one object try:
jQuery.extend(object1[0], object2[2]);
But if you do like this all your properties will be replaced, because they are the same. That is why the above method is best for your case
Related
I have an API array I am practicing with. Below is one object from the array called users. I know in order to access the properties such as the firstName I simply write <h1> {users.firstName} </h1>. However, I am trying to display the address property within the "address" object. I thought it would be <h1> {users.address.address} </h1> but that isn't correct.
{
"id": 1,
"firstName": "Terry",
"lastName": "Medhurst",
"maidenName": "Smitham",
"age": 50,
"gender": "male",
"email": "atuny0#sohu.com",
"phone": "+63 791 675 8914",
"username": "atuny0",
"password": "9uQFF1Lh",
"birthDate": "2000-12-25",
"image": "https://robohash.org/hicveldicta.png",
"bloodGroup": "A−",
"height": 189,
"weight": 75.4,
"eyeColor": "Green",
"hair": {
"color": "Black",
"type": "Strands"
},
"domain": "slashdot.org",
"ip": "117.29.86.254",
"address": {
"address": "1745 T Street Southeast",
"city": "Washington",
"coordinates": {
"lat": 38.867033,
"lng": -76.979235
},
"postalCode": "20020",
"state": "DC"
},
"macAddress": "13:69:BA:56:A3:74",
"university": "Capitol University",
"bank": {
"cardExpire": "06/22",
"cardNumber": "50380955204220685",
"cardType": "maestro",
"currency": "Peso",
"iban": "NO17 0695 2754 967"
},
"company": {
"address": {
"address": "629 Debbie Drive",
"city": "Nashville",
"coordinates": {
"lat": 36.208114,
"lng": -86.58621199999999
},
"postalCode": "37076",
"state": "TN"
},
"department": "Marketing",
"name": "Blanda-O'Keefe",
"title": "Help Desk Operator"
},
"ein": "20-9487066",
"ssn": "661-64-2976",
"userAgent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/12.0.702.0 Safari/534.24"
}
You are most likely not looping over the array. To get the user's address, you need to get every object in the users array, then you can run .address.address on each of those objects. See the snippet below:
const users = [{
"id": 1,
"firstName": "Terry",
"lastName": "Medhurst",
"maidenName": "Smitham",
"age": 50,
"gender": "male",
"email": "atuny0#sohu.com",
"phone": "+63 791 675 8914",
"username": "atuny0",
"password": "9uQFF1Lh",
"birthDate": "2000-12-25",
"image": "https://robohash.org/hicveldicta.png",
"bloodGroup": "A−",
"height": 189,
"weight": 75.4,
"eyeColor": "Green",
"hair": {
"color": "Black",
"type": "Strands"
},
"domain": "slashdot.org",
"ip": "117.29.86.254",
"address": {
"address": "1745 T Street Southeast",
"city": "Washington",
"coordinates": {
"lat": 38.867033,
"lng": -76.979235
},
"postalCode": "20020",
"state": "DC"
},
"macAddress": "13:69:BA:56:A3:74",
"university": "Capitol University",
"bank": {
"cardExpire": "06/22",
"cardNumber": "50380955204220685",
"cardType": "maestro",
"currency": "Peso",
"iban": "NO17 0695 2754 967"
},
"company": {
"address": {
"address": "629 Debbie Drive",
"city": "Nashville",
"coordinates": {
"lat": 36.208114,
"lng": -86.58621199999999
},
"postalCode": "37076",
"state": "TN"
},
"department": "Marketing",
"name": "Blanda-O'Keefe",
"title": "Help Desk Operator"
},
"ein": "20-9487066",
"ssn": "661-64-2976",
"userAgent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/12.0.702.0 Safari/534.24"
}];
function App() {
return users.map(el => <h1>{el.address.address}</h1>);
}
// Render it
ReactDOM.render(<App /> , document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
It appears that you are attempting to access the usersobject.
Verify that it is an array by using the following code: const isUserArray = Array.isArray(users);
If the result is true, use a loop, such as users.map(user => <h1>{user.address.address}</h1>), to iterate through the array and access the address property of each user"
I have to find inside a json array some value of a given key, and return the value of another key of the found object.
I have made this function:
const findValueByKey = ({
jsonArray,
keyToSearch,
valueToSearch,
keyOfTheValueToReturn,
defaultMessage
}) => {
const foundObject = jsonArray.find((obj) => obj[keyToSearch] === valueToSearch);
if (foundObject) return foundObject[keyOfTheValueToReturn];
return defaultMessage || 'not found';
};
But my question is if there's something similar with Lodash, I don't want to reinventing the wheel.
I know that I can find an object given some criteria, like:
_.find(jsonArray, (object) => object[keyToSearch] === valueToSearch);
But then I should extract the key that I need, etc.
You can get the desired result using _.find along with _.get. _.find() will accept an object like { key: value } as the search criterion. Then we can use _.get() to return the desired property. If the key does not exist or the object cannot be found, we'll return defaultMessage.
The sample data comes from jsonplaceholder/users
let data = [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere#april.biz", "phone": "1-770-736-8031 x56442", "website": "hildegard.org", }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna#melissa.tv", "phone": "010-692-6593 x09125", "website": "anastasia.net", }, { "id": 3, "name": "Clementine Bauch", "username": "Samantha", "email": "Nathan#yesenia.net", "phone": "1-463-123-4447", "website": "ramiro.info", }, { "id": 4, "name": "Patricia Lebsack", "username": "Karianne", "email": "Julianne.OConner#kory.org", "phone": "493-170-9623 x156", "website": "kale.biz", }, { "id": 5, "name": "Chelsey Dietrich", "username": "Kamren", "email": "Lucio_Hettinger#annie.ca", "phone": "(254)954-1289", "website": "demarco.info", }, { "id": 6, "name": "Mrs. Dennis Schulist", "username": "Leopoldo_Corkery", "email": "Karley_Dach#jasper.info", "phone": "1-477-935-8478 x6430", "website": "ola.org", }, { "id": 7, "name": "Kurtis Weissnat", "username": "Elwyn.Skiles", "email": "Telly.Hoeger#billy.biz", "phone": "210.067.6132", "website": "elvis.io", }, { "id": 8, "name": "Nicholas Runolfsdottir V", "username": "Maxime_Nienow", "email": "Sherwood#rosamond.me", "phone": "586.493.6943 x140", "website": "jacynthe.com", }, { "id": 9, "name": "Glenna Reichert", "username": "Delphine", "email": "Chaim_McDermott#dana.io", "phone": "(775)976-6794 x41206", "website": "conrad.com", }, { "id": 10, "name": "Clementina DuBuque", "username": "Moriah.Stanton", "email": "Rey.Padberg#karina.biz", "phone": "024-648-3804", "website": "ambrose.net", } ];
function findValueByKey (arr, keyToSearch, valueToSearch, keyOfTheValueToReturn, defaultMessage) {
const obj = _.find(arr, { [keyToSearch]: valueToSearch });
return _.get(obj, keyOfTheValueToReturn, defaultMessage);
}
console.log('Search by username:', findValueByKey(data, 'username', 'Samantha', 'name', 'Not found'))
console.log('Search by website:', findValueByKey(data, 'website', 'hildegard.org', 'name', 'Not found'))
console.log('Default result:', findValueByKey(data, 'keydoesntexist', 'valuedoesntexist', 'name', 'Not found'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
And just for completeness, a vanilla JavaScript solution, using Array.find() along with the in operator
let data = [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere#april.biz", "phone": "1-770-736-8031 x56442", "website": "hildegard.org", }, { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna#melissa.tv", "phone": "010-692-6593 x09125", "website": "anastasia.net", }, { "id": 3, "name": "Clementine Bauch", "username": "Samantha", "email": "Nathan#yesenia.net", "phone": "1-463-123-4447", "website": "ramiro.info", }, { "id": 4, "name": "Patricia Lebsack", "username": "Karianne", "email": "Julianne.OConner#kory.org", "phone": "493-170-9623 x156", "website": "kale.biz", }, { "id": 5, "name": "Chelsey Dietrich", "username": "Kamren", "email": "Lucio_Hettinger#annie.ca", "phone": "(254)954-1289", "website": "demarco.info", }, { "id": 6, "name": "Mrs. Dennis Schulist", "username": "Leopoldo_Corkery", "email": "Karley_Dach#jasper.info", "phone": "1-477-935-8478 x6430", "website": "ola.org", }, { "id": 7, "name": "Kurtis Weissnat", "username": "Elwyn.Skiles", "email": "Telly.Hoeger#billy.biz", "phone": "210.067.6132", "website": "elvis.io", }, { "id": 8, "name": "Nicholas Runolfsdottir V", "username": "Maxime_Nienow", "email": "Sherwood#rosamond.me", "phone": "586.493.6943 x140", "website": "jacynthe.com", }, { "id": 9, "name": "Glenna Reichert", "username": "Delphine", "email": "Chaim_McDermott#dana.io", "phone": "(775)976-6794 x41206", "website": "conrad.com", }, { "id": 10, "name": "Clementina DuBuque", "username": "Moriah.Stanton", "email": "Rey.Padberg#karina.biz", "phone": "024-648-3804", "website": "ambrose.net", } ];
function findValueByKey(arr, keyToSearch, valueToSearch, keyOfTheValueToReturn, defaultMessage) {
const obj = arr.find(el => (el || {}) [keyToSearch] === valueToSearch);
return (keyOfTheValueToReturn in (obj || {})) ? obj[keyOfTheValueToReturn] : defaultMessage;
}
console.log('Search by website:', findValueByKey(data, 'website', 'hildegard.org', 'name', 'Not found'))
I retrieve below-mentioned code snippet as the response of a request
How can I retrieve "id", if I search based on Username in JSON Response
For an example - How can I get a response with "id" value as 1 when I search on the name "Leanne Graham"
Note Response Values and their positions are dynamic
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
}
]
If the username is a unique value, this is a way to do it.
let users = YOUR_JSON_LIST;
let idUser = users.find(u => u.username == SOME_USERNAME).id;
If the search attribute is not constrained to an unique value, you can get a list of values using map
let usersIdList = users
.filter(u => u.website == SOME_WEBSITE)
.map(u => u.id);
I have an array of object as following :
"orders": [
{
"orderID": 1,
"fullName": "xyz",
"email": "xyz#gmail.com",
"phone": "12345",
"flatNo": "A-5",
"complex": "tara tra",
"landmark": null,
"street": null,
"area": "",
"city": "",
"productID": 2,
"name": "curd",
"price": 52,
"image": "curd.png",
"quantity": 1
},
{
"orderID": 1,
"fullName": "xyz",
"email": "xyz#gmail.com",
"phone": "12345",
"flatNo": "A-5",
"complex": "tara tra",
"landmark": null,
"street": null,
"area": "",
"city": "",
"productID": 1,
"name": "lassi",
"price": 65,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 1
},
{
"orderID": 2,
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"productID": 1,
"name": "lassi",
"price": 65,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 3
}
]
Here if the orderID is same for the object I want to merge those object into a single object and create the product information into an array of an object within the main array
Here is the output which I am looking for
"orders": [
{
"orderID": 1,
"fullName": "xyz",
"email": "xyz#gmail.com",
"phone": "12345",
"flatNo": "A-5",
"complex": "tara tra",
"landmark": null,
"street": null,
"area": "",
"city": "",
"products": [
{
"productID": 2,
"name": "curd",
"price": 52,
"image": "curd.png",
"quantity": 1
},
{
"productID": 1,
"name": "lassi",
"price": 65,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 1
}
]
},
{
"orderID": 2,
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"productID": 1,
"name": "lassi",
"price": 65,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 3
}
]
basically I want to combine product information if the order ID is the same.
You'll have an easy time if you use my library for this.
const data = { orders: [ { "orderID": 1, "fullName": "xyz", "email": "xyz#gmail.com", "phone": "12345", "flatNo": "A-5", "complex": "tara tra", "landmark": null, "street": null, "area": "", "city": "", "productID": 2, "name": "curd", "price": 52, "image": "curd.png", "quantity": 1 }, { "orderID": 1, "fullName": "xyz", "email": "xyz#gmail.com", "phone": "12345", "flatNo": "A-5", "complex": "tara tra", "landmark": null, "street": null, "area": "", "city": "", "productID": 1, "name": "lassi", "price": 65, "image": "images\\rtoRAOwj4-conn.PNG", "quantity": 1 }, { "orderID": 2, "fullName": "velocity", "email": "velocity#gmail.com", "phone": "999999", "flatNo": "b-863", "complex": "tara tra", "landmark": "kaskd", "street": "asdasd", "area": "rob city", "city": "asda", "productID": 1, "name": "lassi", "price": 65, "image": "images\\rtoRAOwj4-conn.PNG", "quantity": 3 } ] }
const { pipe, assign, reduce, get, pick, omit } = rubico
const productKeys = ['productID', 'name', 'price', 'image', 'quantity']
const addOrderToMap = (m, order) => {
if (m.has(order.orderID)) {
m.get(order.orderID).products.push(pick(productKeys)(order))
} else {
m.set(order.orderID, {
...omit(productKeys)(order),
products: [pick(productKeys)(order)],
})
}
return m
}
const groupedByOrderID = assign({
orders: pipe([ // assign orders key
get('orders'), // data => orders
reduce(addOrderToMap, new Map()), // orders => Map { orderID -> orderWithProducts }
m => m.values(), // Map { orderID -> orderWithProducts } -> iterator { orderWithProducts }
Array.from, // iterator { orderWithProducts } -> [orderWithProducts]
]),
})(data)
console.log(groupedByOrderID)
<script src="https://unpkg.com/rubico/index.js"></script>
I've commented the code for you, here's the tour if you'd like to learn more.
Just in case if you want to do it through plain JavaScript you can make use of reduce:
var data=[ { "orderID": 1, "fullName": "xyz", "email": "xyz#gmail.com", "phone": "12345", "flatNo": "A-5", "complex": "tara tra", "landmark": null, "street": null, "area": "", "city": "", "productID": 2, "name": "curd", "price": 52, "image": "curd.png", "quantity": 1 }, { "orderID": 1, "fullName": "xyz", "email": "xyz#gmail.com", "phone": "12345", "flatNo": "A-5", "complex": "tara tra", "landmark": null, "street": null, "area": "", "city": "", "productID": 1, "name": "lassi", "price": 65, "image": "images\\rtoRAOwj4-conn.PNG", "quantity": 1 }, { "orderID": 2, "fullName": "velocity", "email": "velocity#gmail.com", "phone": "999999", "flatNo": "b-863", "complex": "tara tra", "landmark": "kaskd", "street": "asdasd", "area": "rob city", "city": "asda", "productID": 1, "name": "lassi", "price": 65, "image": "images\\rtoRAOwj4-conn.PNG", "quantity": 3 } ];
var result = Object.values(data.reduce((acc, {productID, name, price,image, quantity, ...rest})=>{
acc[rest.orderID] = acc[rest.orderID] || {...rest, products:[]};
acc[rest.orderID].products.push({productID, name, price,image, quantity});
return acc;
},{}));
console.log(result);
I was thinking is possible to replace this condition match to a link in the map method.
The end goal, I want to replace address apt #number to be a link after it render.
But the address is wrap with all the text like this:
Kulas Light Apt #556 Gwenborough 92998-3874 to be like:
Kulas Light Apt ${variable} Gwenborough 92998-3874
that variable contain a tag like this
<a href=${data.website}> ${parseInt(numberMatch)} </a>
I don't know how can I just grab that number, and then turn to a link.
Thanks for the help!
const datas = [{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": "Kulas Light Apt #556 Gwenborough 92998-3874",
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": "Kulas Light Apt #123 Gwenborough 92998-3874",
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan#yesenia.net",
"address": "Kulas Light Apt #56 Gwenborough 92998-3874",
"phone": "1-463-123-4447",
"website": "ramiro.info",
"company": {
"name": "Romaguera-Jacobson",
"catchPhrase": "Face to face bifurcated interface",
"bs": "e-enable strategic applications"
}
}
]
const testing = datas.map(data => {
if (data.address.match(/[#][0-9]+/)) {
let numberMatch = data.address.match(/[#][0-9]+/)
numberMatch = `<a href=${data.website}> ${parseInt(numberMatch)} </a>`
}
return (
<div>
<p>id: {data.id}</p>
<p>name: {data.name}</p>
<p>address: {data.address}</p>
</div>
)
})
you could just use replace
const datas = [{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": "Kulas Light Apt #556 Gwenborough 92998-3874",
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": "Kulas Light Apt #123 Gwenborough 92998-3874",
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan#yesenia.net",
"address": "Kulas Light Apt #56 Gwenborough 92998-3874",
"phone": "1-463-123-4447",
"website": "ramiro.info",
"company": {
"name": "Romaguera-Jacobson",
"catchPhrase": "Face to face bifurcated interface",
"bs": "e-enable strategic applications"
}
}
]
const testing = datas.map(({
id,
name,
address,
website
}) => {
return (
`<div>
<p>id: ${id}</p>
<p>name: ${name}</p>
<p>address: ${address.replace(/#\d+/, match => `<a href=${website}> ${match} </a>`)}</p>
</div>`
)
})
console.log(testing);
You can do this at one time using replace method :
the regular expression to be used is /(apt)\s?#(\d+)/i
(apt) apt literally, put in a group to be referenced later in the replacement string.
\s? a space if found.
# a # literally. If you want that to be matched and showed later in the kink's text, add it to the next capturing group.
(\d+) one or more digit. You could use (#\d+) if you want to include the hash sign (but remove the literal matching of it).
the replacement string is $1 <a href=${data.website}>$2</a> :
$1 returns the first capturing group which is apt.
$2 returns the first capturing group which is the digits found after apt #.
datas = [{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": "Kulas Light Apt #556 Gwenborough 92998-3874",
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": "Kulas Light Apt #123 Gwenborough 92998-3874",
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan#yesenia.net",
"address": "Kulas Light Apt #56 Gwenborough 92998-3874",
"phone": "1-463-123-4447",
"website": "ramiro.info",
"company": {
"name": "Romaguera-Jacobson",
"catchPhrase": "Face to face bifurcated interface",
"bs": "e-enable strategic applications"
}
}
], newArr = datas.map(data =>
`<div>
<p>id: ${data.id}</p>
<p>name: ${data.name}</p>
<p>address: ${data.address.replace(/(apt)\s?#(\d+)/i, `$1 <a href=${data.website}>$2</a>`)}</p>
</div>`
);
/** showing the first element in newArr **/
console.log(newArr[0]);
/** output :
<div>
<p>id: 1</p>
<p>name: Leanne Graham</p>
<p>address: Kulas Light Apt <a href=hildegard.org>556</a> Gwenborough 92998-3874</p>
</div>
*/
When you are using match(), it is returning an object. So you have to get the value by fetching as you fetch from an array. Also, you are trying to convert the string starting with "#" through parseInt() which is returning "NaN". You can get your expected output through below code:
const datas = [{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": "Kulas Light Apt #556 Gwenborough 92998-3874",
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": "Kulas Light Apt #123 Gwenborough 92998-3874",
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan#yesenia.net",
"address": "Kulas Light Apt #56 Gwenborough 92998-3874",
"phone": "1-463-123-4447",
"website": "ramiro.info",
"company": {
"name": "Romaguera-Jacobson",
"catchPhrase": "Face to face bifurcated interface",
"bs": "e-enable strategic applications"
}
}
]
let numberMatch
const testing = datas.map(data => {
if (data.address.match(/#[0-9]+/)) {
numberMatch = data.address.match(/#[0-9]+/)
let value = numberMatch.map(val => val)
numberMatch = `<a href=${data.website}> ${value[0]} </a>`
}
return (
<div>
<p>id: {data.id}</p>
<p>name: {data.name}</p>
<p>address: {data.address}</p>
<p>website: {numberMatch}</p>
</div>
)
})
OR
const datas = [{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": "Kulas Light Apt #556 Gwenborough 92998-3874",
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": "Kulas Light Apt #123 Gwenborough 92998-3874",
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan#yesenia.net",
"address": "Kulas Light Apt #56 Gwenborough 92998-3874",
"phone": "1-463-123-4447",
"website": "ramiro.info",
"company": {
"name": "Romaguera-Jacobson",
"catchPhrase": "Face to face bifurcated interface",
"bs": "e-enable strategic applications"
}
}
]
let numberMatch
const testing = datas.map(data => {
if (data.address.match(/#[0-9]+/)) {
numberMatch = data.address.match(/#[0-9]+/)[0]
numberMatch = `<a href=${data.website}> ${numberMatch} </a>`
}
return (
<div>
<p>id: {data.id}</p>
<p>name: {data.name}</p>
<p>address: {data.address}</p>
<p>website: {numberMatch}</p>
</div>
)
})
In the first code, since numberMatch is an object, we are converting it to an array and then taking the first value. In the second code, we are directly taking the data on the basis of the index of the required value. You can check the format of numberMatch in the first code using console.log(numberMatch) . I hope it helps.