#1 2018-03-13 16:09:55

DDGG
Member
Registered: 2018-01-10
Posts: 18

How to change property-names of a Variant efficiently?

I want to change some property-names of a Variant, but after a search I have not found such a function, so I decide to write one:

program Project7;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, SynCommons;

function VariantChangeNames(var V: Variant; const FromNames, ToNames: TRawUTF8DynArray): Boolean;
var
  Name: RawUTF8;
  PData: PDocVariantData;
  Val: Variant;
  i, k: Integer;
begin
  Result := False;
  PData := DocVariantData(V);
  i := 0;
  for Name in FromNames do
  begin
    k := PData^.GetValueIndex(Name);
    if k <> -1 then
    begin
      Val := PData^.Value[k];
      PData^.Value[ToNames[i]] := Val;
      PData^.Delete(k); // If delete before setting value, Val will be incorrect.
      Result := True;
    end;
    Inc(i);
  end;
end;

var
  V: Variant;
begin
  V := TDocVariant.New();
  V.Name := 'John';
  V.Age := 20;
  VariantChangeNames(V, ['Name'], ['RealName']);
  Writeln(VariantToString(V)); // {"Age":20,"RealName":"John"}
end.

VariantChangeNames I wrote is not work efficiently since it needs to do both delete and add, and there is a side effect: the order of names is disrupted.
It seems that directly modify the VName member of the TDocVariantData is the most efficiently way, but it's a private member.

Any advice? Thanks in advance.

Last edited by DDGG (2018-03-13 16:13:02)

Offline

#2 2018-03-13 18:49:03

ab
Administrator
From: France
Registered: 2010-06-21
Posts: 14,272
Website

Re: How to change property-names of a Variant efficiently?

Offline

#3 2018-03-14 03:11:25

DDGG
Member
Registered: 2018-01-10
Posts: 18

Re: How to change property-names of a Variant efficiently?

It's exactly what I want, thanks a lot!

Offline

Board footer

Powered by FluxBB