Can hoek (from hapi.js) transform() function work with arrays?

Exploring the transform() functionality demonstrated in the Hoek documentation, is there a method to transform arrays within the source object?

For instance, modifying the example to work with an array structure, such as this:

var source = {
    address: [
    {
        one: '123 main street',
        two: 'PO Box 1234'
    },
    {
        one: '456 fake street',
        two: 'Apt 2b'
    }],
    title: 'Warehouse',
    state: 'CA'
};

var result = Hoek.transform(source, {
    'person.address.lineOne': 'address.one',
    'person.address.lineTwo': 'address.two',
    'title': 'title',
    'person.address.region': 'state'
});

the output would be:

{
    person: {
        address: {
            lineOne: undefined,
            lineTwo: undefined,
            region: 'CA'
        }
    },
    title: 'Warehouse'
}

UPDATE: introducing expected outcome:

{
    person: {
        address: [{
            lineOne: '123 main street',
            lineTwo: 'PO Box 1234',
            region: 'CA'
        },
        {
            lineOne: '465 fake street',
            lineTwo: 'Apt 2b',
            region: 'CA'
        }]
    },
    title: 'Warehouse'
}

I suspect that what I'm attempting may exceed the capabilities of this function, but I want to confirm it's not due to user error.

If it goes beyond the scope of hoek's transform, do you have any recommendations for efficiently mapping a JS object to a new object while assigning new key names?

Answer №1

The answer provided by @Gergo is now outdated. The Hoek.transform function on the master branch has been updated to accept arrays and iterate through them, transforming each set of keys accordingly.

For more information, you can check out the related PR here: https://github.com/hapijs/hoek/pull/148

You can also refer to the ReadMe on the master branch (to be included in the upcoming release tag v2.15.0): https://github.com/hapijs/hoek/tree/master#transformobj-transform-options

The transform function takes an existing object and transforms it based on the supplied obj and transform map. The options are equivalent to the reach options. Additionally, the first argument can now be an array of objects, resulting in the method returning an array of transformed objects.

Answer №2

Hoek does not have the capability to transform arrays in this manner. It utilizes a one-to-one mapping method, which limits its ability to transform arrays directly. The Hoek.transform() function goes through the keys of the map and retrieves values from the source object using Hoek.reach(), assigning them to a new object:

var keys = Object.keys(transform);

for (var k = 0, kl = keys.length; k < kl; ++k) {
    ...
    res[segment] = exports.reach(source, sourcePath, options);
}

Refer to the source code for more in-depth information. If your task involves simple data manipulation, you can achieve it using plain JavaScript like so:

var result = {
    title: source.title,
    address: []
};

source.address.forEach(function(address) {

    result.address.push({
        lineOne: address.one,
        lineTwo: address.two,
        region: source.state
    });
});

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 function pop cannot be applied to the size of this.items[id]

Currently, I am working on building an array that stores sizes. Populating the array works perfectly and it displays as expected. However, when I attempt to remove an item using .pop();, I encounter the error mentioned in the title above. this.add = f ...

Is there a way to transform JSON into a CSV file using Python?

Is there a way to convert the logs in the JSON format shown below into a CSV file using Python? JSON Input (log.json): {"time":"14472","abc":"0","Def":[{"name":"C","value":77},{"name":"N","value":88}]} {"time":"1447","abc":"1","Def":[{"name":"C","valu ...

Using jQuery to send a POST request with data and retrieve a file via

I am currently developing an application that needs to create and export JSON files containing data. Unfortunately, I do not have the code available on this machine to show you right now, so I'll get straight to the point. The application includes ...

React-dropzone experiencing delays in loading new files for readers

Is there a way to handle conditional responses from an API and assign the desired value to errorMessageUploaded? I'm looking for a solution to receive error messages from the API, but currently, the errormessageupload variable is not being set withou ...

Obtaining a fresh access token from a refresh token using the googleapis npm library

I've been searching everywhere for an explanation, but I can't seem to find one. The documentation I've read says that refresh tokens are used to obtain new access tokens, but it doesn't explain the mechanics behind it. Normally, I wou ...

Transforming JSON into a specialized text structure

After receiving JSON data from the server, I am required to convert it into a different format as shown below: {"1":"82700","2":"26480","3":"31530","4":"22820","5":"15550","6":"205790"} Although I have attempted to achieve this with the provided code sni ...

I'm curious about the origin of this.on event handler. Is it part of a particular library or framework?

While casually perusing through the application.js file in the express source code, I stumbled upon this interesting piece of code. I'm curious about the origin of this '.on' event. Is it part of vanilla JavaScript or is it a feature provid ...

A guide on integrating the MUI Timepicker with the newest 6 version using Formik

I am currently experimenting with the MUI React Timepicker component and facing an issue during integration with Formik for validation. The problem lies in the inability to bind values properly in the initialValues of the form. const [initialValues, setI ...

Finding an element that lacks both a class and an id, and is not consistently present - what's the trick?

Currently, I am faced with a predicament in my code where a <li> element only appears under specific conditions, making it difficult to apply positioning. This element lacks an id and class attribute, which prevents me from targeting it accurately us ...

I am trying to set up an AJAX call in my index.html to connect to a React endpoint, but instead of accessing the intended page, I am getting

I am attempting to execute an AJAX call in my static file index.html to a React endpoint, but instead of the desired response, I am seeing the React homepage. Here is the code snippet from my index.html: <div id="data"></div> <scr ...

Is it possible for a user to include an attachment with their message in a Text prompt during a waterfall step?

Assuming we have the following sequence of steps in our waterfall dialog: self.add_dialog(TextPrompt(TextPrompt.__name__)) self.add_dialog( WaterfallDialog( WaterfallDialog.__name__, [ self.project_step, ...

Using JavaScript/jQuery to analyze POST values just before submission

Currently facing a dilemma as my company is in the process of redesigning its website. I find myself stuck trying to come up with a temporary fix for an issue on the existing site. The solution requires the use of JavaScript or jQuery. The problem arises ...

Enclose several lines of text within a border in the midst of other content

I'm looking to add a stylish border around multiple lines of text in a paragraph without having the border appear on each line individually. While I could enclose all the text in a div, it would separate the content from the rest of the paragraph. W ...

Transfer data to ASP.NET MVC using AJAX and FormData

I am working with a simple model: public class MyModel { public string Description { get; set; } public HttpPostedFileBase File {get; set; } } and I have an MVC action for uploading data: [HttpPost] public ActionResult Upload(List<MyModel> d ...

Having difficulty invoking JavaScript code from PHP

When a button is clicked, this Javascript function is triggered: var xmlhttp; function register() { xmlhttp=GetXmlHttpObject(); alert("pass"); if(xmlhttp==null) { alert("Your browser does not support AJAX!"); return; ...

Mastering the alignment of Material-UI Menu items

When using the menu and menu item components of material-ui to create a select dropdown menu, I encountered an unusual issue where the dropdown menu always expands to the left side of the box, as shown in the image below: https://i.stack.imgur.com/ykRrp.jp ...

The program encountered an issue: Initialization must be completed before utilizing hooks

I'm facing an issue with my new Next app. I added line no. 6 and now I'm getting an error. Can anyone help me understand why? https://i.sstatic.net/lMKH5.png import Head from "next/head"; import Image from "next/image"; impor ...

Why does ajax transmit only the initial input value and not the rest of them?

I recently developed a school website where teachers can input students' marks. Currently, I have organized the project into three main files: The first file is designed to showcase every student's name based on their subject and course. <ta ...

Having difficulty refreshing metadata on the client side within Next.js through client-side data retrieval

Having some trouble with updating metadata using NextSeo when fetching data on the client side. useEffect(()=>{ fetch(assetURL) .then((res) => res.json()) .then((data) => { console.log(data); }) .catch((error) => { console.err ...

"Encountering a Python JSON TypeError while attempting to parse data from

I am relatively new to python and stumbled upon an example that almost fits my needs, but I am encountering errors while trying to parse data from a GET request response. The specific error message I keep facing is: "activity['parameters'][& ...