Combine all JSON objects into a single array and separate the values based on keys containing "meta_value"

I have a JSON object within a single array that was originally a file from which I deleted some fields. Now, I want to modify one of the key values for each entry. Below is an example JSON. I need to iterate through and split the meta_value at

http://www.website/wp-content/uploads/
. Currently, my code is returning every meta_value as undefined instead of splitting the value, which I suspect is due to the loop altering the key value before splitting.

Any assistance would be greatly appreciated.

Here is the code I have created so far that generates the JSON data at the end.

var exclusions = [
"ID", "post_author", "post_date_gmt", "post_excerpt", "comment_status", 
"ping_status", "post_password", "to_ping" ,"pinged", "post_modified","post_name",
"post_modified_gmt", "post_content_filtered", "guid", "menu_order", "post_mime_type",
"comment_count", "meta_id", "post_id", "post_type", "post_status"
];
var a = JSON.parse(fs.readFileSync('final.json'));

a.forEach(obj=>{
  exclusions.forEach(excl=>{
    if(obj[excl] || obj[excl] === ""){
      delete obj[excl];
    }

    if(obj["meta_value"] !== undefined){

      let objTest = obj["meta_value"].split('http://www.fsd.ca/wp-content/uploads/')[1];

      obj["meta_value"] = objTest;


    }

  });
});

console.log(a);

JSON after initial exclusions

[
  {
    post_date: '2012-02-16 23:37:22',
    post_content: `Today we worked at literacy centres. We are writing our own Three Bears story. We are reading with Mrs.Kitson, writing in our life books, working in our printing books and working on making words on the iPads. We use the apps Pocket phonics, magnet board and Montessori crosswords. We went to the library. In the afternoon we went to the gym and watched a play by Quest Theatre. It was called <span style="text-decoration: underline;">For</span> <span style="text-decoration: underline;">Art's Sake.</span> They told us that we are all artists and that we should use our imagination. We did zumba. We danced to The chihuahua song. We went to the DPA room and played different tag games. Our hearts worked hard. We had a fun day!`,
    post_title: 'Hometime',
    meta_value: 'http://www.fsd.ca/wp-content/uploads/2012/02/SN850631.jpg'
  },
  ...
]
  1. List item

JSON after changing the meta_value key value, where every value is undefined

[
{
    post_date: '2012-02-16 23:37:22',
    post_content: `Today we worked at literacy centres. We are writing our own Three Bears story. We are reading with Mrs.Kitson, writing in our life books, working in our printing books and working on making words on the iPads. We use the apps Pocket phonics, magnet board and Montessori crosswords. We went to the library. In the afternoon we went to the gym and watched a play by Quest Theatre. It was called <span style="text-decoration: underline;">For</span> <span style="text-decoration: underline;">Art's Sake.</span> They told us that we are all artists and that we should use our imagination. We did zumba. We danced to The chihuahua song. We went to the DPA room and played different tag games. Our hearts worked hard. We had a fun day!`,
    post_title: 'Hometime',
    meta_value: undefined
  },
  ...
]

Answer №1

The issue arises when attempting to modify obj["meta_value"] within the exclusions.forEach() loop. This causes it to execute multiple times for the same object. During the first iteration, it replaces

'http://www.mrskitson.ca/wp-content/uploads/2012/02/SN850631.jpg'
with '2012/02/SN850631.jpg'. However, on subsequent runs, the delimiter
'http://www.mrskitson.ca/wp-content/'
is not found in the meta value, resulting in a split() that returns an array with only 1 element, making [1] undefined.

To resolve this, move the modification outside of the inner loop to ensure proper functionality.

var exclusions = [
  "ID", "post_author", "post_date_gmt", "post_excerpt", "comment_status",
  "ping_status", "post_password", "to_ping", "pinged", "post_modified", "post_name",
  "post_modified_gmt", "post_content_filtered", "guid", "menu_order", "post_mime_type",
  "comment_count", "meta_id", "post_id", "post_type", "post_status"
];
var a = [
  {
    post_date: '2012-02-16 23:37:22',
    post_content: `Today we worked at literacy centres. We are writing our own Three Bears story. We are reading with Mrs.Kitson, writing in our life books, working in our printing books and working on making words on the iPads. We use the apps Pocket phonics, magnet board and Montessori crosswords. We went to the library. In the afternoon we went to the gym and watched a play by Quest Theatre. It was called <span style="text-decoration: underline;">For</span> <span style="text-decoration: underline;">Art's Sake.</span> They told us that we are all artists and that we should use our imagination. We did zumba. We danced to The chihuahua song. We went to the DPA room and played different tag games. Our hearts worked hard. We had a fun day!`,
    post_title: 'Hometime',
    meta_value: 'http://www.mrskitson.ca/wp-content/uploads/2012/02/SN850631.jpg'
  },
  {
    post_date: '2012-02-21 20:39:19',
    post_content: 'Today we started making our castles. We painted them colourful tissue paper. We are writing our own fairy tales. We read The Princess Frog Fairy Tale. We are making clay dragons and sewing puppets. We went to the gym and skipped. We wrote in our life books an practiced our printing. We had a fun day!',
    post_title: 'Creating Castles',
    meta_value: 'http://www.mrskitson.ca/wp-content/uploads/2012/02/SN850649.jpg'
  },
  {
    post_date: '2012-02-23 21:30:55',
    post_content: 'We talked about the letter E. E is a vowel. There is a vowel in every word. We did our E sheets. We went skating. We had hot chocolate after skating. We worked at new literacy centers. We are doing hard work. We went to Music. We played the bumble bee game. We went to the DPA room to play tag and dance. We went to centers and to the library. We had a fun day!',
    post_title: 'We Have New Pillows',
    meta_value: 'http://www.mrskitson.ca/wp-content/uploads/2012/02/SN850660.jpg'
  },
  {
    post_date: '2012-02-24 19:06:39',
    post_content: 'Today it was Hawaii Day. We wore shorts and summer clothes. We made a Chicka Chicka Boom Boom picture. We made leis. We ate batter dipped pineapples and ate mango, pineapple, papaya, starfruit, dragon fruit and coconut. We tried coconut water. We did the limbo and danced Hawaii style. We sat on our towels and played a math game where we guessed how many candies were under the cup. We wrote in our life books and we went to the big park. We had a fun, fun day!',
    post_title: 'Hawaii Day',
    meta_value: 'http://www.mrskitson.ca/wp-content/uploads/2012/02/SN850665.jpg'
  },
];

a.forEach(obj => {
  exclusions.forEach(excl => {
    if (obj[excl] || obj[excl] === "") {
      delete obj[excl];
    }
  });
  if (obj["meta_value"] !== undefined) {
    let objTest = obj["meta_value"].split('http://www.mrskitson.ca/wp-content/uploads/')[1];
    obj["meta_value"] = objTest
  }
});

console.log(a);

Answer №2

When working with the code below, ensure that obj["meta_value"].split('')[1]; will return an empty array if split() is used. It is important to handle the case where the 0th element does not exist in the array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The margin-top property in CSS is not functioning as intended for a specific pixel value when applied to

I'm having trouble with positioning an icon using margin-top: -35px; under #menu. When I click on the icon, the side navigation bar doesn't work properly. However, if I adjust it to -15px, the side navigation bar displays correctly. Can someone h ...

Dynamic Filtering with Reactjs Autocomplete Component (Material UI) using API calls on each input modification

Just starting out with Reactjs and looking to build an Autocomplete component that fetches API data on every input change to update the options. I've been using the Autocomplete component from Material UI but struggling to get it working as expected. ...

Programming the tab pages within Chrome

By using JavaScript, I successfully opened a new tab at www.blogger.com from the Main.html page. <script> window.open("https://www.blogger.com"); </script> I am now on the blogger page. My goal is to automatically scroll to the end of the bl ...

The title tag's ng-bind should be placed outside of the element

When using ng-bind for the title tag inside the header, it seems to produce unexpected behavior. Here is an example of the code: <title page-title ng-bind="page_title"></title> and this is the resulting output: My Page Sucks <titl ...

The issue arises when attempting to execute an Ajax function within a JQuery append method, causing malfunction

My JQuery append function is calling an ajax function within the onChange method. Here is my code snippet: var data='<?php echo $data; ?>'; var tambah=1; var txt=1; function add_fullboard_dalam_kota(){ function showU(str) { ...

Link Google Map Marker Click Event with Dynamic Binding

I'm currently working on binding a click event to a link that is positioned outside the Google Map Canvas. The goal is to open an "infowindow" on a map marker when this link is clicked. While I know how to achieve this for a specific point, I need a d ...

Refreshing SQL Server data using an HTML form

In the table below: <table id="skuTable" role="grid"> <thead> <th class="skuRow">Order</th> <th>Fab. Date</th> <th class="skuRow">Norder</th> <th>Color</th> ...

Tips for establishing a fixed point at which divs cease to shrink as the browser size decreases

There are numerous dynamically designed websites where divs or images shrink as the browser size decreases. A great example of this is http://en.wikipedia.org/wiki/Main_Page The div containing the text shrinks proportionally to the browser size until it ...

Tips for choosing elements based on the length of an array

When using an each function, I scan the DOM to find multiple elements with a specific className. Depending on the length of this ClassName, it will create an array that is either 2 or 4 elements long. I need to distinguish between these two types of elem ...

JQuery UI Autocomplete - Issue with loading data object

I've been attempting to implement autocomplete with JQuery UI, but I'm encountering difficulties when passing in a label & value object. var individuals = []; var test = new Array(); var dataObject = jQuery.parseJSON(data) ...

How to assign a global variable in Angular 2 from within a promise

I have encountered a strange issue while trying to assign a response to a global variable inside an observable. Here's the logic of my program: Fetch the latest playlists IDs from elastic search (using a type definition file for elastic search). T ...

Validating the length of form inputs and selected items from a dropdown menu

I have the following form and I am attempting to validate its states as follows: themeName is required and should have a minimum of 4 characters. themeLangFrom selected value cannot be the same as themeLangTo (and vice versa). I want to display a span er ...

Array of Numpy containing elements with various dimensions on the last axis

Consider the code snippet below: import numpy as np x = np.random.random([2, 4, 50]) y = np.random.random([2, 4, 60]) z = [x, y] z = np.array(z, dtype=object) An error ValueError: could not broadcast input array from shape (2,4,50) into shape (2,4) occu ...

Is it achievable to modify the appearance of the "Saved Password" style on Firefox?

After creating a login page that initially had a certain aesthetic, I encountered an issue when saving login data in Firefox. The saved login page took on a yellow-ish tint that was not present in my original design: https://i.sstatic.net/LURG3.png I am ...

Having issues retrieving data from an ArcGis Database?

Currently, I am attempting to extract age information from a particular map. To find the relevant data, please navigate to the "Cases By County" section of this map and click on the right arrow once: View Map Here. Following advice from a helpful source o ...

Using ng-if to compare dates in AngularJS without considering the year

I am facing a comparison issue with dates in my code. I have one date that is hardcoded as the first day of the month, and another date coming from the database (stored in a JSON object). When I compare these dates using ng-if, it seems to ignore the year ...

Updating the load context variable in Django template after making changes via an AJAX call: a step-by-step guide

Here is the code snippet for displaying table items in my customer_items.html page: <table id="tblData" style="width: 100% !important;" class="display table table-bordered table-striped table-condensed"> <thead> <tr> ...

Is your Javascript navigation functioning properly on some submenus while encountering issues on others?

If you visit , you'll notice that it's a visually appealing site. The navigation submenus seem to be functioning properly, HOWEVER upon inspecting the element, you'll notice that under the PRICING tab, there are submenus that have the same c ...

Exploring the differences between using a local controller in Angular's MdDialog modal versus displaying a shadow at

I've been attempting to utilize an app-level controller to showcase a modal dialog. The local function controller tests are functioning flawlessly, but the app level controller is only showing a grey shadow instead of the expected dialog. The edit an ...

Fetching Data from JSON Object Using PHP

My goal is to extract specific objects from the data stored in a .json file. I am particularly interested in accessing the individual items within the stylers object. However, I am encountering difficulties in retrieving information related to color or vis ...